Coverage Report

Created: 2023-03-13 03:44

/src/DLXEmu/external/imgui/imgui.cpp
Line
Count
Source (jump to first uncovered line)
1
// dear imgui, v1.89.4 WIP
2
// (main code and documentation)
3
4
// Help:
5
// - Read FAQ at http://dearimgui.org/faq
6
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
7
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
8
// Read imgui.cpp for details, links and comments.
9
10
// Resources:
11
// - FAQ                   http://dearimgui.org/faq
12
// - Homepage & latest     https://github.com/ocornut/imgui
13
// - Releases & changelog  https://github.com/ocornut/imgui/releases
14
// - Gallery               https://github.com/ocornut/imgui/issues/5886 (please post your screenshots/video there!)
15
// - Wiki                  https://github.com/ocornut/imgui/wiki (lots of good stuff there)
16
// - Glossary              https://github.com/ocornut/imgui/wiki/Glossary
17
// - Issues & support      https://github.com/ocornut/imgui/issues
18
19
// Getting Started?
20
// - For first-time users having issues compiling/linking/running or issues loading fonts:
21
//   please post in https://github.com/ocornut/imgui/discussions if you cannot find a solution in resources above.
22
23
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
24
// See LICENSE.txt for copyright and licensing details (standard MIT License).
25
// This library is free but needs your support to sustain development and maintenance.
26
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
27
// Individuals: you can support continued development via donations. See docs/README or web page.
28
29
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
30
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
31
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
32
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
33
// to a better solution or official support for them.
34
35
/*
36
37
Index of this file:
38
39
DOCUMENTATION
40
41
- MISSION STATEMENT
42
- END-USER GUIDE
43
- PROGRAMMER GUIDE
44
  - READ FIRST
45
  - HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
46
  - GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
47
  - HOW A SIMPLE APPLICATION MAY LOOK LIKE
48
  - HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
49
  - USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
50
- API BREAKING CHANGES (read me when you update!)
51
- FREQUENTLY ASKED QUESTIONS (FAQ)
52
  - Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
53
54
CODE
55
(search for "[SECTION]" in the code to find them)
56
57
// [SECTION] INCLUDES
58
// [SECTION] FORWARD DECLARATIONS
59
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
60
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
61
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
62
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
63
// [SECTION] MISC HELPERS/UTILITIES (File functions)
64
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
65
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
66
// [SECTION] ImGuiStorage
67
// [SECTION] ImGuiTextFilter
68
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
69
// [SECTION] ImGuiListClipper
70
// [SECTION] STYLING
71
// [SECTION] RENDER HELPERS
72
// [SECTION] INITIALIZATION, SHUTDOWN
73
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
74
// [SECTION] INPUTS
75
// [SECTION] ERROR CHECKING
76
// [SECTION] LAYOUT
77
// [SECTION] SCROLLING
78
// [SECTION] TOOLTIPS
79
// [SECTION] POPUPS
80
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
81
// [SECTION] DRAG AND DROP
82
// [SECTION] LOGGING/CAPTURING
83
// [SECTION] SETTINGS
84
// [SECTION] LOCALIZATION
85
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
86
// [SECTION] DOCKING
87
// [SECTION] PLATFORM DEPENDENT HELPERS
88
// [SECTION] METRICS/DEBUGGER WINDOW
89
// [SECTION] DEBUG LOG WINDOW
90
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
91
92
*/
93
94
//-----------------------------------------------------------------------------
95
// DOCUMENTATION
96
//-----------------------------------------------------------------------------
97
98
/*
99
100
 MISSION STATEMENT
101
 =================
102
103
 - Easy to use to create code-driven and data-driven tools.
104
 - Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
105
 - Easy to hack and improve.
106
 - Minimize setup and maintenance.
107
 - Minimize state storage on user side.
108
 - Minimize state synchronization.
109
 - Portable, minimize dependencies, run on target (consoles, phones, etc.).
110
 - Efficient runtime and memory consumption.
111
112
 Designed for developers and content-creators, not the typical end-user! Some of the current weaknesses includes:
113
114
 - Doesn't look fancy, doesn't animate.
115
 - Limited layout features, intricate layouts are typically crafted in code.
116
117
118
 END-USER GUIDE
119
 ==============
120
121
 - Double-click on title bar to collapse window.
122
 - Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
123
 - Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
124
 - Click and drag on any empty space to move window.
125
 - TAB/SHIFT+TAB to cycle through keyboard editable fields.
126
 - CTRL+Click on a slider or drag box to input value as text.
127
 - Use mouse wheel to scroll.
128
 - Text editor:
129
   - Hold SHIFT or use mouse to select text.
130
   - CTRL+Left/Right to word jump.
131
   - CTRL+Shift+Left/Right to select words.
132
   - CTRL+A or Double-Click to select all.
133
   - CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
134
   - CTRL+Z,CTRL+Y to undo/redo.
135
   - ESCAPE to revert text to its original value.
136
   - Controls are automatically adjusted for OSX to match standard OSX text editing operations.
137
 - General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
138
 - General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. Download controller mapping PNG/PSD at http://dearimgui.org/controls_sheets
139
140
141
 PROGRAMMER GUIDE
142
 ================
143
144
 READ FIRST
145
 ----------
146
 - Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
147
 - Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
148
   destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
149
 - Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
150
 - The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
151
 - Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
152
   You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
153
 - Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
154
   For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
155
   where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
156
 - Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
157
 - This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
158
 - Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
159
   If you get an assert, read the messages and comments around the assert.
160
 - C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
161
 - C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
162
   See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
163
   However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
164
 - C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
165
166
167
 HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
168
 ----------------------------------------------
169
 - Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
170
 - Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
171
 - You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
172
 - Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
173
   If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
174
   from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
175
   likely be a comment about it. Please report any issue to the GitHub page!
176
 - To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
177
 - Try to keep your copy of Dear ImGui reasonably up to date.
178
179
180
 GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
181
 ---------------------------------------------------------------
182
 - Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
183
 - In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
184
 - Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
185
   It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
186
 - You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
187
 - When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
188
 - Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
189
   Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
190
   phases of your own application. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
191
 - Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
192
 - If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
193
194
195
 HOW A SIMPLE APPLICATION MAY LOOK LIKE
196
 --------------------------------------
197
 EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
198
 The sub-folders in examples/ contain examples applications following this structure.
199
200
     // Application init: create a dear imgui context, setup some options, load fonts
201
     ImGui::CreateContext();
202
     ImGuiIO& io = ImGui::GetIO();
203
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
204
     // TODO: Fill optional fields of the io structure later.
205
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
206
207
     // Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
208
     ImGui_ImplWin32_Init(hwnd);
209
     ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
210
211
     // Application main loop
212
     while (true)
213
     {
214
         // Feed inputs to dear imgui, start new frame
215
         ImGui_ImplDX11_NewFrame();
216
         ImGui_ImplWin32_NewFrame();
217
         ImGui::NewFrame();
218
219
         // Any application code here
220
         ImGui::Text("Hello, world!");
221
222
         // Render dear imgui into screen
223
         ImGui::Render();
224
         ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
225
         g_pSwapChain->Present(1, 0);
226
     }
227
228
     // Shutdown
229
     ImGui_ImplDX11_Shutdown();
230
     ImGui_ImplWin32_Shutdown();
231
     ImGui::DestroyContext();
232
233
 EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
234
235
     // Application init: create a dear imgui context, setup some options, load fonts
236
     ImGui::CreateContext();
237
     ImGuiIO& io = ImGui::GetIO();
238
     // TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
239
     // TODO: Fill optional fields of the io structure later.
240
     // TODO: Load TTF/OTF fonts if you don't want to use the default font.
241
242
     // Build and load the texture atlas into a texture
243
     // (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
244
     int width, height;
245
     unsigned char* pixels = NULL;
246
     io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
247
248
     // At this point you've got the texture data and you need to upload that to your graphic system:
249
     // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
250
     // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
251
     MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
252
     io.Fonts->SetTexID((void*)texture);
253
254
     // Application main loop
255
     while (true)
256
     {
257
        // Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
258
        // (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
259
        io.DeltaTime = 1.0f/60.0f;              // set the time elapsed since the previous frame (in seconds)
260
        io.DisplaySize.x = 1920.0f;             // set the current display width
261
        io.DisplaySize.y = 1280.0f;             // set the current display height here
262
        io.AddMousePosEvent(mouse_x, mouse_y);  // update mouse position
263
        io.AddMouseButtonEvent(0, mouse_b[0]);  // update mouse button states
264
        io.AddMouseButtonEvent(1, mouse_b[1]);  // update mouse button states
265
266
        // Call NewFrame(), after this point you can use ImGui::* functions anytime
267
        // (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
268
        ImGui::NewFrame();
269
270
        // Most of your application code here
271
        ImGui::Text("Hello, world!");
272
        MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
273
        MyGameRender(); // may use any Dear ImGui functions as well!
274
275
        // Render dear imgui, swap buffers
276
        // (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
277
        ImGui::EndFrame();
278
        ImGui::Render();
279
        ImDrawData* draw_data = ImGui::GetDrawData();
280
        MyImGuiRenderFunction(draw_data);
281
        SwapBuffers();
282
     }
283
284
     // Shutdown
285
     ImGui::DestroyContext();
286
287
 To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
288
 you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
289
 Please read the FAQ and example applications for details about this!
290
291
292
 HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
293
 ---------------------------------------------
294
 The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
295
296
    void MyImGuiRenderFunction(ImDrawData* draw_data)
297
    {
298
       // TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
299
       // TODO: Setup texture sampling state: sample with bilinear filtering (NOT point/nearest filtering). Use 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines;' to allow point/nearest filtering.
300
       // TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
301
       // TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
302
       // TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
303
       ImVec2 clip_off = draw_data->DisplayPos;
304
       for (int n = 0; n < draw_data->CmdListsCount; n++)
305
       {
306
          const ImDrawList* cmd_list = draw_data->CmdLists[n];
307
          const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data;  // vertex buffer generated by Dear ImGui
308
          const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data;   // index buffer generated by Dear ImGui
309
          for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
310
          {
311
             const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
312
             if (pcmd->UserCallback)
313
             {
314
                 pcmd->UserCallback(cmd_list, pcmd);
315
             }
316
             else
317
             {
318
                 // Project scissor/clipping rectangles into framebuffer space
319
                 ImVec2 clip_min(pcmd->ClipRect.x - clip_off.x, pcmd->ClipRect.y - clip_off.y);
320
                 ImVec2 clip_max(pcmd->ClipRect.z - clip_off.x, pcmd->ClipRect.w - clip_off.y);
321
                 if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
322
                     continue;
323
324
                 // We are using scissoring to clip some objects. All low-level graphics API should support it.
325
                 // - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
326
                 //   (some elements visible outside their bounds) but you can fix that once everything else works!
327
                 // - Clipping coordinates are provided in imgui coordinates space:
328
                 //   - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
329
                 //   - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
330
                 //   - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
331
                 //     always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
332
                 // - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
333
                 MyEngineSetScissor(clip_min.x, clip_min.y, clip_max.x, clip_max.y);
334
335
                 // The texture for the draw call is specified by pcmd->GetTexID().
336
                 // The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
337
                 MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
338
339
                 // Render 'pcmd->ElemCount/3' indexed triangles.
340
                 // By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
341
                 MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer + pcmd->IdxOffset, vtx_buffer, pcmd->VtxOffset);
342
             }
343
          }
344
       }
345
    }
346
347
348
 USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
349
 ------------------------------------------
350
 - The gamepad/keyboard navigation is fairly functional and keeps being improved.
351
 - Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PlayStation, Switch, Xbox) without a mouse!
352
 - The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
353
 - Keyboard:
354
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
355
    - When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard),
356
      the io.WantCaptureKeyboard flag will be set. For more advanced uses, you may want to read from:
357
       - io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
358
       - io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
359
       - or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
360
      Please reach out if you think the game vs navigation input sharing could be improved.
361
 - Gamepad:
362
    - Application: Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
363
    - Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + call io.AddKeyEvent/AddKeyAnalogEvent() with ImGuiKey_Gamepad_XXX keys.
364
      For analog values (0.0f to 1.0f), backend is responsible to handling a dead-zone and rescaling inputs accordingly.
365
      Backend code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
366
    - BEFORE 1.87, BACKENDS USED TO WRITE TO io.NavInputs[]. This is now obsolete. Please call io functions instead!
367
    - You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://dearimgui.org/controls_sheets
368
    - If you need to share inputs between your game and the Dear ImGui interface, the easiest approach is to go all-or-nothing,
369
      with a buttons combo to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
370
 - Mouse:
371
    - PS4/PS5 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
372
    - Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
373
    - On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
374
      Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
375
      When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
376
      When that happens your backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends in examples/ do that.
377
      (If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse moving back and forth!)
378
      (In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
379
       to set a boolean to ignore your other external mouse positions until the external source is moved again.)
380
381
382
 API BREAKING CHANGES
383
 ====================
384
385
 Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
386
 Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
387
 When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
388
 You can read releases logs https://github.com/ocornut/imgui/releases for more details.
389
390
(Docking/Viewport Branch)
391
 - 2023/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
392
                        - reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
393
                          you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
394
                        - likewise io.MousePos and GetMousePos() will use OS coordinates.
395
                          If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
396
397
 - 2023/02/07 (1.89.3) - backends: renamed "imgui_impl_sdl.cpp" to "imgui_impl_sdl2.cpp" and "imgui_impl_sdl.h" to "imgui_impl_sdl2.h". (#6146) This is in prevision for the future release of SDL3.
398
 - 2022/10/26 (1.89) - commented out redirecting OpenPopupContextItem() which was briefly the name of OpenPopupOnItemClick() from 1.77 to 1.79.
399
 - 2022/10/12 (1.89) - removed runtime patching of invalid "%f"/"%0.f" format strings for DragInt()/SliderInt(). This was obsoleted in 1.61 (May 2018). See 1.61 changelog for details.
400
 - 2022/09/26 (1.89) - renamed and merged keyboard modifiers key enums and flags into a same set. Kept inline redirection enums (will obsolete).
401
                         - ImGuiKey_ModCtrl  and ImGuiModFlags_Ctrl  -> ImGuiMod_Ctrl
402
                         - ImGuiKey_ModShift and ImGuiModFlags_Shift -> ImGuiMod_Shift
403
                         - ImGuiKey_ModAlt   and ImGuiModFlags_Alt   -> ImGuiMod_Alt
404
                         - ImGuiKey_ModSuper and ImGuiModFlags_Super -> ImGuiMod_Super
405
                       the ImGuiKey_ModXXX were introduced in 1.87 and mostly used by backends.
406
                       the ImGuiModFlags_XXX have been exposed in imgui.h but not really used by any public api only by third-party extensions.
407
                       exceptionally commenting out the older ImGuiKeyModFlags_XXX names ahead of obsolescence schedule to reduce confusion and because they were not meant to be used anyway.
408
 - 2022/09/20 (1.89) - ImGuiKey is now a typed enum, allowing ImGuiKey_XXX symbols to be named in debuggers.
409
                       this will require uses of legacy backend-dependent indices to be casted, e.g.
410
                          - with imgui_impl_glfw:  IsKeyPressed(GLFW_KEY_A) -> IsKeyPressed((ImGuiKey)GLFW_KEY_A);
411
                          - with imgui_impl_win32: IsKeyPressed('A')        -> IsKeyPressed((ImGuiKey)'A')
412
                          - etc. However if you are upgrading code you might well use the better, backend-agnostic IsKeyPressed(ImGuiKey_A) now!
413
 - 2022/09/12 (1.89) - removed the bizarre legacy default argument for 'TreePush(const void* ptr = NULL)', always pass a pointer value explicitly. NULL/nullptr is ok but require cast, e.g. TreePush((void*)nullptr);
414
 - 2022/09/05 (1.89) - commented out redirecting functions/enums names that were marked obsolete in 1.77 and 1.78 (June 2020):
415
                         - DragScalar(), DragScalarN(), DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
416
                         - SliderScalar(), SliderScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(): For old signatures ending with (..., const char* format, float power = 1.0f) -> use (..., format ImGuiSliderFlags_Logarithmic) if power != 1.0f.
417
                         - BeginPopupContextWindow(const char*, ImGuiMouseButton, bool) -> use BeginPopupContextWindow(const char*, ImGuiPopupFlags)
418
 - 2022/09/02 (1.89) - obsoleted using SetCursorPos()/SetCursorScreenPos() to extend parent window/cell boundaries.
419
                       this relates to when moving the cursor position beyond current boundaries WITHOUT submitting an item.
420
                         - previously this would make the window content size ~200x200:
421
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();
422
                         - instead, please submit an item:
423
                              Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End();
424
                         - alternative:
425
                              Begin(...) + Dummy(ImVec2(200,200)) + End();
426
                         - content size is now only extended when submitting an item!
427
                         - with '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will now be detected and assert.
428
                         - without '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' this will silently be fixed until we obsolete it.
429
 - 2022/08/03 (1.89) - changed signature of ImageButton() function. Kept redirection function (will obsolete).
430
                        - added 'const char* str_id' parameter + removed 'int frame_padding = -1' parameter.
431
                        - old signature: bool ImageButton(ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), int frame_padding = -1, ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
432
                          - used the ImTextureID value to create an ID. This was inconsistent with other functions, led to ID conflicts, and caused problems with engines using transient ImTextureID values.
433
                          - had a FramePadding override which was inconsistent with other functions and made the already-long signature even longer.
434
                        - new signature: bool ImageButton(const char* str_id, ImTextureID tex_id, ImVec2 size, ImVec2 uv0 = ImVec2(0,0), ImVec2 uv1 = ImVec2(1,1), ImVec4 bg_col = ImVec4(0,0,0,0), ImVec4 tint_col = ImVec4(1,1,1,1));
435
                          - requires an explicit identifier. You may still use e.g. PushID() calls and then pass an empty identifier.
436
                          - always uses style.FramePadding for padding, to be consistent with other buttons. You may use PushStyleVar() to alter this.
437
 - 2022/07/08 (1.89) - inputs: removed io.NavInputs[] and ImGuiNavInput enum (following 1.87 changes).
438
                        - Official backends from 1.87+                  -> no issue.
439
                        - Official backends from 1.60 to 1.86           -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need updating!
440
                        - Custom backends not writing to io.NavInputs[] -> no issue.
441
                        - Custom backends writing to io.NavInputs[]     -> will build and convert gamepad inputs, unless IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Need fixing!
442
                        - TL;DR: Backends should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values instead of filling io.NavInput[].
443
 - 2022/06/15 (1.88) - renamed IMGUI_DISABLE_METRICS_WINDOW to IMGUI_DISABLE_DEBUG_TOOLS for correctness. kept support for old define (will obsolete).
444
 - 2022/05/03 (1.88) - backends: osx: removed ImGui_ImplOSX_HandleEvent() from backend API in favor of backend automatically handling event capture. All ImGui_ImplOSX_HandleEvent() calls should be removed as they are now unnecessary.
445
 - 2022/04/05 (1.88) - inputs: renamed ImGuiKeyModFlags to ImGuiModFlags. Kept inline redirection enums (will obsolete). This was never used in public API functions but technically present in imgui.h and ImGuiIO.
446
 - 2022/01/20 (1.87) - inputs: reworded gamepad IO.
447
                        - Backend writing to io.NavInputs[]            -> backend should call io.AddKeyEvent()/io.AddKeyAnalogEvent() with ImGuiKey_GamepadXXX values.
448
 - 2022/01/19 (1.87) - sliders, drags: removed support for legacy arithmetic operators (+,+-,*,/) when inputing text. This doesn't break any api/code but a feature that used to be accessible by end-users (which seemingly no one used).
449
 - 2022/01/17 (1.87) - inputs: reworked mouse IO.
450
                        - Backend writing to io.MousePos               -> backend should call io.AddMousePosEvent()
451
                        - Backend writing to io.MouseDown[]            -> backend should call io.AddMouseButtonEvent()
452
                        - Backend writing to io.MouseWheel             -> backend should call io.AddMouseWheelEvent()
453
                        - Backend writing to io.MouseHoveredViewport   -> backend should call io.AddMouseViewportEvent() [Docking branch w/ multi-viewports only]
454
                       note: for all calls to IO new functions, the Dear ImGui context should be bound/current.
455
                       read https://github.com/ocornut/imgui/issues/4921 for details.
456
 - 2022/01/10 (1.87) - inputs: reworked keyboard IO. Removed io.KeyMap[], io.KeysDown[] in favor of calling io.AddKeyEvent(). Removed GetKeyIndex(), now unecessary. All IsKeyXXX() functions now take ImGuiKey values. All features are still functional until IMGUI_DISABLE_OBSOLETE_KEYIO is defined. Read Changelog and Release Notes for details.
457
                        - IsKeyPressed(MY_NATIVE_KEY_XXX)              -> use IsKeyPressed(ImGuiKey_XXX)
458
                        - IsKeyPressed(GetKeyIndex(ImGuiKey_XXX))      -> use IsKeyPressed(ImGuiKey_XXX)
459
                        - Backend writing to io.KeyMap[],io.KeysDown[] -> backend should call io.AddKeyEvent() (+ call io.SetKeyEventNativeData() if you want legacy user code to stil function with legacy key codes).
460
                        - Backend writing to io.KeyCtrl, io.KeyShift.. -> backend should call io.AddKeyEvent() with ImGuiMod_XXX values. *IF YOU PULLED CODE BETWEEN 2021/01/10 and 2021/01/27: We used to have a io.AddKeyModsEvent() function which was now replaced by io.AddKeyEvent() with ImGuiMod_XXX values.*
461
                     - one case won't work with backward compatibility: if your custom backend used ImGuiKey as mock native indices (e.g. "io.KeyMap[ImGuiKey_A] = ImGuiKey_A") because those values are now larger than the legacy KeyDown[] array. Will assert.
462
                     - inputs: added ImGuiKey_ModCtrl/ImGuiKey_ModShift/ImGuiKey_ModAlt/ImGuiKey_ModSuper values to submit keyboard modifiers using io.AddKeyEvent(), instead of writing directly to io.KeyCtrl, io.KeyShift, io.KeyAlt, io.KeySuper.
463
 - 2022/01/05 (1.87) - inputs: renamed ImGuiKey_KeyPadEnter to ImGuiKey_KeypadEnter to align with new symbols. Kept redirection enum.
464
 - 2022/01/05 (1.87) - removed io.ImeSetInputScreenPosFn() in favor of more flexible io.SetPlatformImeDataFn(). Removed 'void* io.ImeWindowHandle' in favor of writing to 'void* ImGuiViewport::PlatformHandleRaw'.
465
 - 2022/01/01 (1.87) - commented out redirecting functions/enums names that were marked obsolete in 1.69, 1.70, 1.71, 1.72 (March-July 2019)
466
                        - ImGui::SetNextTreeNodeOpen()        -> use ImGui::SetNextItemOpen()
467
                        - ImGui::GetContentRegionAvailWidth() -> use ImGui::GetContentRegionAvail().x
468
                        - ImGui::TreeAdvanceToLabelPos()      -> use ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetTreeNodeToLabelSpacing());
469
                        - ImFontAtlas::CustomRect             -> use ImFontAtlasCustomRect
470
                        - ImGuiColorEditFlags_RGB/HSV/HEX     -> use ImGuiColorEditFlags_DisplayRGB/HSV/Hex
471
 - 2021/12/20 (1.86) - backends: removed obsolete Marmalade backend (imgui_impl_marmalade.cpp) + example. Find last supported version at https://github.com/ocornut/imgui/wiki/Bindings
472
 - 2021/11/04 (1.86) - removed CalcListClipping() function. Prefer using ImGuiListClipper which can return non-contiguous ranges. Please open an issue if you think you really need this function.
473
 - 2021/08/23 (1.85) - removed GetWindowContentRegionWidth() function. keep inline redirection helper. can use 'GetWindowContentRegionMax().x - GetWindowContentRegionMin().x' instead for generally 'GetContentRegionAvail().x' is more useful.
474
 - 2021/07/26 (1.84) - commented out redirecting functions/enums names that were marked obsolete in 1.67 and 1.69 (March 2019):
475
                        - ImGui::GetOverlayDrawList() -> use ImGui::GetForegroundDrawList()
476
                        - ImFont::GlyphRangesBuilder  -> use ImFontGlyphRangesBuilder
477
 - 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
478
                        - if you are using official backends from the source tree: you have nothing to do.
479
                        - if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
480
 - 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
481
                        - ImDrawCornerFlags_TopLeft  -> use ImDrawFlags_RoundCornersTopLeft
482
                        - ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
483
                        - ImDrawCornerFlags_None     -> use ImDrawFlags_RoundCornersNone etc.
484
                       flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
485
                       breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
486
                        - rounding == 0.0f + flags == 0 --> meant no rounding  --> unchanged (common use)
487
                        - rounding  > 0.0f + flags != 0 --> meant rounding     --> unchanged (common use)
488
                        - rounding == 0.0f + flags != 0 --> meant no rounding  --> unchanged (unlikely use)
489
                        - rounding  > 0.0f + flags == 0 --> meant no rounding  --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
490
                       this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
491
                       the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
492
                       legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
493
 - 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
494
                        - ImGui::SetScrollHere()              -> use ImGui::SetScrollHereY()
495
 - 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
496
 - 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
497
 - 2021/02/22 (1.82) - (*undone in 1.84*) win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file  with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
498
 - 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
499
 - 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
500
                     - removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
501
                     - renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
502
 - 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
503
                     - renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
504
                     - renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
505
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
506
                        - ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
507
                        - ImGuiCol_ModalWindowDarkening       -> use ImGuiCol_ModalWindowDimBg
508
                        - ImGuiInputTextCallback              -> use ImGuiTextEditCallback
509
                        - ImGuiInputTextCallbackData          -> use ImGuiTextEditCallbackData
510
 - 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
511
 - 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
512
 - 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
513
 - 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
514
 - 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
515
 - 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
516
                        - io.RenderDrawListsFn pointer        -> use ImGui::GetDrawData() value and call the render function of your backend
517
                        - ImGui::IsAnyWindowFocused()         -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
518
                        - ImGui::IsAnyWindowHovered()         -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
519
                        - ImGuiStyleVar_Count_                -> use ImGuiStyleVar_COUNT
520
                        - ImGuiMouseCursor_Count_             -> use ImGuiMouseCursor_COUNT
521
                      - removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
522
                        - InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
523
                        - same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
524
 - 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
525
 - 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
526
 - 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
527
 - 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
528
 - 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
529
 - 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
530
 - 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
531
                       replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
532
                       worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
533
                       - if you omitted the 'power' parameter (likely!), you are not affected.
534
                       - if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
535
                       - if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
536
                       see https://github.com/ocornut/imgui/issues/3361 for all details.
537
                       kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
538
                       for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
539
                     - obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
540
 - 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
541
 - 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
542
 - 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
543
 - 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
544
 - 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
545
 - 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
546
 - 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
547
 - 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
548
                       - ShowTestWindow()                    -> use ShowDemoWindow()
549
                       - IsRootWindowFocused()               -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
550
                       - IsRootWindowOrAnyChildFocused()     -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
551
                       - SetNextWindowContentWidth(w)        -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
552
                       - GetItemsLineHeightWithSpacing()     -> use GetFrameHeightWithSpacing()
553
                       - ImGuiCol_ChildWindowBg              -> use ImGuiCol_ChildBg
554
                       - ImGuiStyleVar_ChildWindowRounding   -> use ImGuiStyleVar_ChildRounding
555
                       - ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
556
                       - IMGUI_DISABLE_TEST_WINDOWS          -> use IMGUI_DISABLE_DEMO_WINDOWS
557
 - 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
558
 - 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
559
 - 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
560
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
561
 - 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
562
 - 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
563
                       - Begin() [old 5 args version]        -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
564
                       - IsRootWindowOrAnyChildHovered()     -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
565
                       - AlignFirstTextHeightToWidgets()     -> use AlignTextToFramePadding()
566
                       - SetNextWindowPosCenter()            -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
567
                       - ImFont::Glyph                       -> use ImFontGlyph
568
 - 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
569
                       if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
570
                       The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
571
                       If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
572
 - 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
573
 - 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
574
 - 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
575
 - 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
576
                       overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
577
                       This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
578
                       Please reach out if you are affected.
579
 - 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
580
 - 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
581
 - 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
582
 - 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
583
 - 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
584
 - 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
585
 - 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
586
 - 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
587
 - 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
588
 - 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
589
 - 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
590
 - 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
591
 - 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
592
 - 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
593
 - 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
594
                       If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
595
 - 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
596
 - 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
597
                       NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
598
                       Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
599
 - 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
600
 - 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
601
 - 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
602
 - 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
603
 - 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
604
 - 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
605
 - 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
606
 - 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan,  etc.).
607
                       old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
608
                       when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
609
                       in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
610
 - 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
611
 - 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
612
 - 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
613
                       If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
614
                       To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
615
                       If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
616
 - 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
617
                       consistent with other functions. Kept redirection functions (will obsolete).
618
 - 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
619
 - 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some backend ahead of merging the Nav branch).
620
 - 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
621
 - 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
622
 - 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
623
 - 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
624
 - 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
625
 - 2018/02/07 (1.60) - reorganized context handling to be more explicit,
626
                       - YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
627
                       - removed Shutdown() function, as DestroyContext() serve this purpose.
628
                       - you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
629
                       - removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
630
                       - removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
631
 - 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
632
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
633
 - 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
634
 - 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
635
 - 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
636
 - 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
637
 - 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
638
 - 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
639
 - 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
640
 - 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
641
 - 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
642
                     - obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
643
 - 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
644
 - 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
645
 - 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
646
 - 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
647
                       Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
648
 - 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
649
 - 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
650
 - 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
651
 - 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
652
 - 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
653
 - 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
654
 - 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
655
                       removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
656
                         IsItemHoveredRect()        --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
657
                         IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
658
                         IsMouseHoveringWindow()    --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
659
 - 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
660
 - 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
661
 - 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (will obsolete).
662
 - 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
663
 - 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your backend if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
664
 - 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
665
                     - renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
666
                     - renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
667
 - 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
668
 - 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
669
 - 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame type.
670
 - 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
671
 - 2017/08/13 (1.51) - renamed ImGuiCol_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
672
 - 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. Kept redirection enums (will obsolete).
673
 - 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
674
 - 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
675
                     - changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
676
                     - changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0, 0))'
677
 - 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
678
 - 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
679
 - 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
680
 - 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetID() and use it instead of passing string to BeginChild().
681
 - 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
682
 - 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
683
 - 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully, breakage should be minimal.
684
 - 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
685
                       If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you, otherwise if <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
686
                       This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color:
687
                       ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col) { float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a; return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a); }
688
                       If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
689
 - 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
690
 - 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
691
 - 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
692
 - 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
693
 - 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref GitHub issue #337).
694
 - 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
695
 - 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
696
 - 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
697
 - 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
698
 - 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
699
 - 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
700
 - 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
701
                       GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
702
                       GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
703
 - 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
704
 - 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
705
 - 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
706
 - 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
707
                       you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
708
 - 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
709
                       this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
710
                     - if you are using a vanilla copy of one of the imgui_impl_XXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
711
                     - the signature of the io.RenderDrawListsFn handler has changed!
712
                       old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
713
                       new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
714
                         parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
715
                         ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
716
                         ImDrawCmd:  'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
717
                     - each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
718
                     - if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
719
                     - refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
720
 - 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
721
 - 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
722
 - 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
723
 - 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
724
 - 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely used. Sorry!
725
 - 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
726
 - 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
727
 - 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
728
 - 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
729
 - 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
730
 - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
731
 - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
732
 - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
733
 - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
734
 - 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
735
 - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
736
 - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
737
 - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
738
 - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
739
 - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
740
 - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
741
 - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
742
 - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
743
 - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
744
 - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
745
 - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
746
 - 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
747
                       - old:  const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
748
                       - new:  unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
749
                       you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. It is now recommended that you sample the font texture with bilinear interpolation.
750
 - 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
751
 - 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
752
 - 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
753
 - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
754
 - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
755
 - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
756
 - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
757
 - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
758
 - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
759
 - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
760
 - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
761
 - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
762
 - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
763
 - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
764
765
766
 FREQUENTLY ASKED QUESTIONS (FAQ)
767
 ================================
768
769
 Read all answers online:
770
   https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
771
 Read all answers locally (with a text editor or ideally a Markdown viewer):
772
   docs/FAQ.md
773
 Some answers are copied down here to facilitate searching in code.
774
775
 Q&A: Basics
776
 ===========
777
778
 Q: Where is the documentation?
779
 A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
780
    - Run the examples/ and explore them.
781
    - See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
782
    - The demo covers most features of Dear ImGui, so you can read the code and see its output.
783
    - See documentation and comments at the top of imgui.cpp + effectively imgui.h.
784
    - Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
785
      examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
786
    - The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
787
    - The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
788
    - Your programming IDE is your friend, find the type or function declaration to find comments
789
      associated with it.
790
791
 Q: What is this library called?
792
 Q: Which version should I get?
793
 >> This library is called "Dear ImGui", please don't call it "ImGui" :)
794
 >> See https://www.dearimgui.org/faq for details.
795
796
 Q&A: Integration
797
 ================
798
799
 Q: How to get started?
800
 A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
801
802
 Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
803
 A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
804
 >> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
805
806
 Q. How can I enable keyboard controls?
807
 Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
808
 Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
809
 Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
810
 Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
811
 >> See https://www.dearimgui.org/faq
812
813
 Q&A: Usage
814
 ----------
815
816
 Q: About the ID Stack system..
817
   - Why is my widget not reacting when I click on it?
818
   - How can I have widgets with an empty label?
819
   - How can I have multiple widgets with the same label?
820
   - How can I have multiple windows with the same label?
821
 Q: How can I display an image? What is ImTextureID, how does it work?
822
 Q: How can I use my own math types instead of ImVec2/ImVec4?
823
 Q: How can I interact with standard C++ types (such as std::string and std::vector)?
824
 Q: How can I display custom shapes? (using low-level ImDrawList API)
825
 >> See https://www.dearimgui.org/faq
826
827
 Q&A: Fonts, Text
828
 ================
829
830
 Q: How should I handle DPI in my application?
831
 Q: How can I load a different font than the default?
832
 Q: How can I easily use icons in my application?
833
 Q: How can I load multiple fonts?
834
 Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
835
 >> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
836
837
 Q&A: Concerns
838
 =============
839
840
 Q: Who uses Dear ImGui?
841
 Q: Can you create elaborate/serious tools with Dear ImGui?
842
 Q: Can you reskin the look of Dear ImGui?
843
 Q: Why using C++ (as opposed to C)?
844
 >> See https://www.dearimgui.org/faq
845
846
 Q&A: Community
847
 ==============
848
849
 Q: How can I help?
850
 A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
851
      We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
852
      This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
853
    - Individuals: you can support continued development via PayPal donations. See README.
854
    - If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
855
      and see how you want to help and can help!
856
    - Disclose your usage of Dear ImGui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
857
      You may post screenshot or links in the gallery threads. Visuals are ideal as they inspire other programmers.
858
      But even without visuals, disclosing your use of dear imgui helps the library grow credibility, and help other teams and programmers with taking decisions.
859
    - If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on GitHub or privately).
860
861
*/
862
863
//-------------------------------------------------------------------------
864
// [SECTION] INCLUDES
865
//-------------------------------------------------------------------------
866
867
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
868
#define _CRT_SECURE_NO_WARNINGS
869
#endif
870
871
#include "imgui.h"
872
#ifndef IMGUI_DISABLE
873
874
#ifndef IMGUI_DEFINE_MATH_OPERATORS
875
#define IMGUI_DEFINE_MATH_OPERATORS
876
#endif
877
#include "imgui_internal.h"
878
879
// System includes
880
#include <stdio.h>      // vsnprintf, sscanf, printf
881
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
882
#include <stddef.h>     // intptr_t
883
#else
884
#include <stdint.h>     // intptr_t
885
#endif
886
887
// [Windows] On non-Visual Studio compilers, we default to IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS unless explicitly enabled
888
#if defined(_WIN32) && !defined(_MSC_VER) && !defined(IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
889
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
890
#endif
891
892
// [Windows] OS specific includes (optional)
893
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
894
#define IMGUI_DISABLE_WIN32_FUNCTIONS
895
#endif
896
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
897
#ifndef WIN32_LEAN_AND_MEAN
898
#define WIN32_LEAN_AND_MEAN
899
#endif
900
#ifndef NOMINMAX
901
#define NOMINMAX
902
#endif
903
#ifndef __MINGW32__
904
#include <Windows.h>        // _wfopen, OpenClipboard
905
#else
906
#include <windows.h>
907
#endif
908
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
909
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
910
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
911
#endif
912
#endif
913
914
// [Apple] OS specific includes
915
#if defined(__APPLE__)
916
#include <TargetConditionals.h>
917
#endif
918
919
// Visual Studio warnings
920
#ifdef _MSC_VER
921
#pragma warning (disable: 4127)             // condition expression is constant
922
#pragma warning (disable: 4996)             // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
923
#if defined(_MSC_VER) && _MSC_VER >= 1922   // MSVC 2019 16.2 or later
924
#pragma warning (disable: 5054)             // operator '|': deprecated between enumerations of different types
925
#endif
926
#pragma warning (disable: 26451)            // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to an 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
927
#pragma warning (disable: 26495)            // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
928
#pragma warning (disable: 26812)            // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
929
#endif
930
931
// Clang/GCC warnings with -Weverything
932
#if defined(__clang__)
933
#if __has_warning("-Wunknown-warning-option")
934
#pragma clang diagnostic ignored "-Wunknown-warning-option"         // warning: unknown warning group 'xxx'                      // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
935
#endif
936
#pragma clang diagnostic ignored "-Wunknown-pragmas"                // warning: unknown warning group 'xxx'
937
#pragma clang diagnostic ignored "-Wold-style-cast"                 // warning: use of old-style cast                            // yes, they are more terse.
938
#pragma clang diagnostic ignored "-Wfloat-equal"                    // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
939
#pragma clang diagnostic ignored "-Wformat-nonliteral"              // warning: format string is not a string literal            // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
940
#pragma clang diagnostic ignored "-Wexit-time-destructors"          // warning: declaration requires an exit-time destructor     // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
941
#pragma clang diagnostic ignored "-Wglobal-constructors"            // warning: declaration requires a global destructor         // similar to above, not sure what the exact difference is.
942
#pragma clang diagnostic ignored "-Wsign-conversion"                // warning: implicit conversion changes signedness
943
#pragma clang diagnostic ignored "-Wformat-pedantic"                // warning: format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
944
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast"       // warning: cast to 'void *' from smaller integer type 'int'
945
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"  // warning: zero as null pointer constant                    // some standard header variations use #define NULL 0
946
#pragma clang diagnostic ignored "-Wdouble-promotion"               // warning: implicit conversion from 'float' to 'double' when passing argument to function  // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
947
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion"  // warning: implicit conversion from 'xxx' to 'float' may lose precision
948
#elif defined(__GNUC__)
949
// We disable -Wpragmas because GCC doesn't provide a has_warning equivalent and some forks/patches may not follow the warning/version association.
950
#pragma GCC diagnostic ignored "-Wpragmas"                  // warning: unknown option after '#pragma GCC diagnostic' kind
951
#pragma GCC diagnostic ignored "-Wunused-function"          // warning: 'xxxx' defined but not used
952
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast"      // warning: cast to pointer from integer of different size
953
#pragma GCC diagnostic ignored "-Wformat"                   // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
954
#pragma GCC diagnostic ignored "-Wdouble-promotion"         // warning: implicit conversion from 'float' to 'double' when passing argument to function
955
#pragma GCC diagnostic ignored "-Wconversion"               // warning: conversion to 'xxxx' from 'xxxx' may alter its value
956
#pragma GCC diagnostic ignored "-Wformat-nonliteral"        // warning: format not a string literal, format string not checked
957
#pragma GCC diagnostic ignored "-Wstrict-overflow"          // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
958
#pragma GCC diagnostic ignored "-Wclass-memaccess"          // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
959
#endif
960
961
// Debug options
962
72.8k
#define IMGUI_DEBUG_NAV_SCORING     0   // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
963
#define IMGUI_DEBUG_NAV_RECTS       0   // Display the reference navigation rectangle for each window
964
#define IMGUI_DEBUG_INI_SETTINGS    0   // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
965
966
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
967
static const float NAV_WINDOWING_HIGHLIGHT_DELAY            = 0.20f;    // Time before the highlight and screen dimming starts fading in
968
static const float NAV_WINDOWING_LIST_APPEAR_DELAY          = 0.15f;    // Time before the window list starts to appear
969
970
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
971
static const float WINDOWS_HOVER_PADDING                    = 4.0f;     // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
972
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f;    // Reduce visual noise by only highlighting the border after a certain time.
973
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER    = 0.70f;    // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
974
975
// Docking
976
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA        = 0.50f;    // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
977
static const float DOCKING_SPLITTER_SIZE                    = 2.0f;
978
979
//-------------------------------------------------------------------------
980
// [SECTION] FORWARD DECLARATIONS
981
//-------------------------------------------------------------------------
982
983
static void             SetCurrentWindow(ImGuiWindow* window);
984
static void             FindHoveredWindow();
985
static ImGuiWindow*     CreateNewWindow(const char* name, ImGuiWindowFlags flags);
986
static ImVec2           CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
987
988
static void             AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
989
static void             AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
990
991
// Settings
992
static void             WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
993
static void*            WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
994
static void             WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
995
static void             WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
996
static void             WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
997
998
// Platform Dependents default implementation for IO functions
999
static const char*      GetClipboardTextFn_DefaultImpl(void* user_data);
1000
static void             SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
1001
static void             SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data);
1002
1003
namespace ImGui
1004
{
1005
// Navigation
1006
static void             NavUpdate();
1007
static void             NavUpdateWindowing();
1008
static void             NavUpdateWindowingOverlay();
1009
static void             NavUpdateCancelRequest();
1010
static void             NavUpdateCreateMoveRequest();
1011
static void             NavUpdateCreateTabbingRequest();
1012
static float            NavUpdatePageUpPageDown();
1013
static inline void      NavUpdateAnyRequestFlag();
1014
static void             NavUpdateCreateWrappingRequest();
1015
static void             NavEndFrame();
1016
static bool             NavScoreItem(ImGuiNavItemData* result);
1017
static void             NavApplyItemToResult(ImGuiNavItemData* result);
1018
static void             NavProcessItem();
1019
static void             NavProcessItemForTabbingRequest(ImGuiID id);
1020
static ImVec2           NavCalcPreferredRefPos();
1021
static void             NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
1022
static ImGuiWindow*     NavRestoreLastChildNavWindow(ImGuiWindow* window);
1023
static void             NavRestoreLayer(ImGuiNavLayer layer);
1024
static void             NavRestoreHighlightAfterMove();
1025
static int              FindWindowFocusIndex(ImGuiWindow* window);
1026
1027
// Error Checking and Debug Tools
1028
static void             ErrorCheckNewFrameSanityChecks();
1029
static void             ErrorCheckEndFrameSanityChecks();
1030
static void             UpdateDebugToolItemPicker();
1031
static void             UpdateDebugToolStackQueries();
1032
1033
// Inputs
1034
static void             UpdateKeyboardInputs();
1035
static void             UpdateMouseInputs();
1036
static void             UpdateMouseWheel();
1037
static void             UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt);
1038
1039
// Misc
1040
static void             UpdateSettings();
1041
static bool             UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
1042
static void             RenderWindowOuterBorders(ImGuiWindow* window);
1043
static void             RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
1044
static void             RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
1045
static void             RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col);
1046
static void             RenderDimmedBackgrounds();
1047
static ImGuiWindow*     FindBlockingModal(ImGuiWindow* window);
1048
1049
// Viewports
1050
const ImGuiID           IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
1051
static ImGuiViewportP*  AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
1052
static void             DestroyViewport(ImGuiViewportP* viewport);
1053
static void             UpdateViewportsNewFrame();
1054
static void             UpdateViewportsEndFrame();
1055
static void             WindowSelectViewport(ImGuiWindow* window);
1056
static void             WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack);
1057
static bool             UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
1058
static bool             UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window);
1059
static bool             GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
1060
static int              FindPlatformMonitorForPos(const ImVec2& pos);
1061
static int              FindPlatformMonitorForRect(const ImRect& r);
1062
static void             UpdateViewportPlatformMonitor(ImGuiViewportP* viewport);
1063
1064
}
1065
1066
//-----------------------------------------------------------------------------
1067
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
1068
//-----------------------------------------------------------------------------
1069
1070
// DLL users:
1071
// - Heaps and globals are not shared across DLL boundaries!
1072
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
1073
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
1074
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
1075
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
1076
1077
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
1078
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
1079
//   Change to a different context by calling ImGui::SetCurrentContext().
1080
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
1081
//   If you want thread-safety to allow N threads to access N different contexts:
1082
//   - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
1083
//         struct ImGuiContext;
1084
//         extern thread_local ImGuiContext* MyImGuiTLS;
1085
//         #define GImGui MyImGuiTLS
1086
//     And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
1087
//   - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
1088
//   - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
1089
// - DLL users: read comments above.
1090
#ifndef GImGui
1091
ImGuiContext*   GImGui = NULL;
1092
#endif
1093
1094
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
1095
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
1096
// - DLL users: read comments above.
1097
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
1098
1.22k
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); return malloc(size); }
1099
1.17k
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); free(ptr); }
1100
#else
1101
static void*   MallocWrapper(size_t size, void* user_data)    { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
1102
static void    FreeWrapper(void* ptr, void* user_data)        { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
1103
#endif
1104
static ImGuiMemAllocFunc    GImAllocatorAllocFunc = MallocWrapper;
1105
static ImGuiMemFreeFunc     GImAllocatorFreeFunc = FreeWrapper;
1106
static void*                GImAllocatorUserData = NULL;
1107
1108
//-----------------------------------------------------------------------------
1109
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
1110
//-----------------------------------------------------------------------------
1111
1112
ImGuiStyle::ImGuiStyle()
1113
1
{
1114
1
    Alpha                   = 1.0f;             // Global alpha applies to everything in Dear ImGui.
1115
1
    DisabledAlpha           = 0.60f;            // Additional alpha multiplier applied by BeginDisabled(). Multiply over current value of Alpha.
1116
1
    WindowPadding           = ImVec2(8,8);      // Padding within a window
1117
1
    WindowRounding          = 0.0f;             // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
1118
1
    WindowBorderSize        = 1.0f;             // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1119
1
    WindowMinSize           = ImVec2(32,32);    // Minimum window size
1120
1
    WindowTitleAlign        = ImVec2(0.0f,0.5f);// Alignment for title bar text
1121
1
    WindowMenuButtonPosition= ImGuiDir_Left;    // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
1122
1
    ChildRounding           = 0.0f;             // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
1123
1
    ChildBorderSize         = 1.0f;             // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1124
1
    PopupRounding           = 0.0f;             // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
1125
1
    PopupBorderSize         = 1.0f;             // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
1126
1
    FramePadding            = ImVec2(4,3);      // Padding within a framed rectangle (used by most widgets)
1127
1
    FrameRounding           = 0.0f;             // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
1128
1
    FrameBorderSize         = 0.0f;             // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
1129
1
    ItemSpacing             = ImVec2(8,4);      // Horizontal and vertical spacing between widgets/lines
1130
1
    ItemInnerSpacing        = ImVec2(4,4);      // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
1131
1
    CellPadding             = ImVec2(4,2);      // Padding within a table cell
1132
1
    TouchExtraPadding       = ImVec2(0,0);      // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
1133
1
    IndentSpacing           = 21.0f;            // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
1134
1
    ColumnsMinSpacing       = 6.0f;             // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
1135
1
    ScrollbarSize           = 14.0f;            // Width of the vertical scrollbar, Height of the horizontal scrollbar
1136
1
    ScrollbarRounding       = 9.0f;             // Radius of grab corners rounding for scrollbar
1137
1
    GrabMinSize             = 12.0f;            // Minimum width/height of a grab box for slider/scrollbar
1138
1
    GrabRounding            = 0.0f;             // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
1139
1
    LogSliderDeadzone       = 4.0f;             // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
1140
1
    TabRounding             = 4.0f;             // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
1141
1
    TabBorderSize           = 0.0f;             // Thickness of border around tabs.
1142
1
    TabMinWidthForCloseButton = 0.0f;           // Minimum width for close button to appear on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
1143
1
    ColorButtonPosition     = ImGuiDir_Right;   // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
1144
1
    ButtonTextAlign         = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
1145
1
    SelectableTextAlign     = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
1146
1
    SeparatorTextBorderSize = 3.0f;             // Thickkness of border in SeparatorText()
1147
1
    SeparatorTextAlign      = ImVec2(0.0f,0.5f);// Alignment of text within the separator. Defaults to (0.0f, 0.5f) (left aligned, center).
1148
1
    SeparatorTextPadding    = ImVec2(20.0f,3.f);// Horizontal offset of text from each edge of the separator + spacing on other axis. Generally small values. .y is recommended to be == FramePadding.y.
1149
1
    DisplayWindowPadding    = ImVec2(19,19);    // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
1150
1
    DisplaySafeAreaPadding  = ImVec2(3,3);      // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
1151
1
    MouseCursorScale        = 1.0f;             // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
1152
1
    AntiAliasedLines        = true;             // Enable anti-aliased lines/borders. Disable if you are really tight on CPU/GPU.
1153
1
    AntiAliasedLinesUseTex  = true;             // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering (NOT point/nearest filtering).
1154
1
    AntiAliasedFill         = true;             // Enable anti-aliased filled shapes (rounded rectangles, circles, etc.).
1155
1
    CurveTessellationTol    = 1.25f;            // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
1156
1
    CircleTessellationMaxError = 0.30f;         // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
1157
1158
    // Default theme
1159
1
    ImGui::StyleColorsDark(this);
1160
1
}
1161
1162
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
1163
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
1164
void ImGuiStyle::ScaleAllSizes(float scale_factor)
1165
0
{
1166
0
    WindowPadding = ImFloor(WindowPadding * scale_factor);
1167
0
    WindowRounding = ImFloor(WindowRounding * scale_factor);
1168
0
    WindowMinSize = ImFloor(WindowMinSize * scale_factor);
1169
0
    ChildRounding = ImFloor(ChildRounding * scale_factor);
1170
0
    PopupRounding = ImFloor(PopupRounding * scale_factor);
1171
0
    FramePadding = ImFloor(FramePadding * scale_factor);
1172
0
    FrameRounding = ImFloor(FrameRounding * scale_factor);
1173
0
    ItemSpacing = ImFloor(ItemSpacing * scale_factor);
1174
0
    ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
1175
0
    CellPadding = ImFloor(CellPadding * scale_factor);
1176
0
    TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
1177
0
    IndentSpacing = ImFloor(IndentSpacing * scale_factor);
1178
0
    ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
1179
0
    ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
1180
0
    ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
1181
0
    GrabMinSize = ImFloor(GrabMinSize * scale_factor);
1182
0
    GrabRounding = ImFloor(GrabRounding * scale_factor);
1183
0
    LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
1184
0
    TabRounding = ImFloor(TabRounding * scale_factor);
1185
0
    TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
1186
0
    SeparatorTextPadding = ImFloor(SeparatorTextPadding * scale_factor);
1187
0
    DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
1188
0
    DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
1189
0
    MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
1190
0
}
1191
1192
ImGuiIO::ImGuiIO()
1193
1
{
1194
    // Most fields are initialized with zero
1195
1
    memset(this, 0, sizeof(*this));
1196
1
    IM_STATIC_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT);
1197
1198
    // Settings
1199
1
    ConfigFlags = ImGuiConfigFlags_None;
1200
1
    BackendFlags = ImGuiBackendFlags_None;
1201
1
    DisplaySize = ImVec2(-1.0f, -1.0f);
1202
1
    DeltaTime = 1.0f / 60.0f;
1203
1
    IniSavingRate = 5.0f;
1204
1
    IniFilename = "imgui.ini"; // Important: "imgui.ini" is relative to current working dir, most apps will want to lock this to an absolute path (e.g. same path as executables).
1205
1
    LogFilename = "imgui_log.txt";
1206
1
    MouseDoubleClickTime = 0.30f;
1207
1
    MouseDoubleClickMaxDist = 6.0f;
1208
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1209
    for (int i = 0; i < ImGuiKey_COUNT; i++)
1210
        KeyMap[i] = -1;
1211
#endif
1212
1
    KeyRepeatDelay = 0.275f;
1213
1
    KeyRepeatRate = 0.050f;
1214
1
    HoverDelayNormal = 0.30f;
1215
1
    HoverDelayShort = 0.10f;
1216
1
    UserData = NULL;
1217
1218
1
    Fonts = NULL;
1219
1
    FontGlobalScale = 1.0f;
1220
1
    FontDefault = NULL;
1221
1
    FontAllowUserScaling = false;
1222
1
    DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
1223
1224
    // Docking options (when ImGuiConfigFlags_DockingEnable is set)
1225
1
    ConfigDockingNoSplit = false;
1226
1
    ConfigDockingWithShift = false;
1227
1
    ConfigDockingAlwaysTabBar = false;
1228
1
    ConfigDockingTransparentPayload = false;
1229
1230
    // Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
1231
1
    ConfigViewportsNoAutoMerge = false;
1232
1
    ConfigViewportsNoTaskBarIcon = false;
1233
1
    ConfigViewportsNoDecoration = true;
1234
1
    ConfigViewportsNoDefaultParent = false;
1235
1236
    // Miscellaneous options
1237
1
    MouseDrawCursor = false;
1238
#ifdef __APPLE__
1239
    ConfigMacOSXBehaviors = true;  // Set Mac OS X style defaults based on __APPLE__ compile time flag
1240
#else
1241
1
    ConfigMacOSXBehaviors = false;
1242
1
#endif
1243
1
    ConfigInputTrickleEventQueue = true;
1244
1
    ConfigInputTextCursorBlink = true;
1245
1
    ConfigInputTextEnterKeepActive = false;
1246
1
    ConfigDragClickToInputText = false;
1247
1
    ConfigWindowsResizeFromEdges = true;
1248
1
    ConfigWindowsMoveFromTitleBarOnly = false;
1249
1
    ConfigMemoryCompactTimer = 60.0f;
1250
1251
    // Platform Functions
1252
1
    BackendPlatformName = BackendRendererName = NULL;
1253
1
    BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
1254
1
    GetClipboardTextFn = GetClipboardTextFn_DefaultImpl;   // Platform dependent default implementations
1255
1
    SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
1256
1
    ClipboardUserData = NULL;
1257
1
    SetPlatformImeDataFn = SetPlatformImeDataFn_DefaultImpl;
1258
1259
    // Input (NB: we already have memset zero the entire structure!)
1260
1
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1261
1
    MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
1262
1
    MouseDragThreshold = 6.0f;
1263
6
    for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
1264
141
    for (int i = 0; i < IM_ARRAYSIZE(KeysData); i++) { KeysData[i].DownDuration = KeysData[i].DownDurationPrev = -1.0f; }
1265
1
    AppAcceptingEvents = true;
1266
1
    BackendUsingLegacyKeyArrays = (ImS8)-1;
1267
1
    BackendUsingLegacyNavInputArray = true; // assume using legacy array until proven wrong
1268
1
}
1269
1270
// Pass in translated ASCII characters for text input.
1271
// - with glfw you can get those from the callback set in glfwSetCharCallback()
1272
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
1273
// FIXME: Should in theory be called "AddCharacterEvent()" to be consistent with new API
1274
void ImGuiIO::AddInputCharacter(unsigned int c)
1275
5.92k
{
1276
5.92k
    ImGuiContext& g = *GImGui;
1277
5.92k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1278
5.92k
    if (c == 0 || !AppAcceptingEvents)
1279
2.54k
        return;
1280
1281
3.38k
    ImGuiInputEvent e;
1282
3.38k
    e.Type = ImGuiInputEventType_Text;
1283
3.38k
    e.Source = ImGuiInputSource_Keyboard;
1284
3.38k
    e.Text.Char = c;
1285
3.38k
    g.InputEventsQueue.push_back(e);
1286
3.38k
}
1287
1288
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
1289
// we should save the high surrogate.
1290
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
1291
1.46k
{
1292
1.46k
    if ((c == 0 && InputQueueSurrogate == 0) || !AppAcceptingEvents)
1293
81
        return;
1294
1295
1.38k
    if ((c & 0xFC00) == 0xD800) // High surrogate, must save
1296
662
    {
1297
662
        if (InputQueueSurrogate != 0)
1298
202
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1299
662
        InputQueueSurrogate = c;
1300
662
        return;
1301
662
    }
1302
1303
725
    ImWchar cp = c;
1304
725
    if (InputQueueSurrogate != 0)
1305
449
    {
1306
449
        if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
1307
431
        {
1308
431
            AddInputCharacter(IM_UNICODE_CODEPOINT_INVALID);
1309
431
        }
1310
18
        else
1311
18
        {
1312
18
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
1313
18
            cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
1314
#else
1315
            cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
1316
#endif
1317
18
        }
1318
1319
449
        InputQueueSurrogate = 0;
1320
449
    }
1321
725
    AddInputCharacter((unsigned)cp);
1322
725
}
1323
1324
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
1325
54
{
1326
54
    if (!AppAcceptingEvents)
1327
0
        return;
1328
54
    while (*utf8_chars != 0)
1329
0
    {
1330
0
        unsigned int c = 0;
1331
0
        utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
1332
0
        AddInputCharacter(c);
1333
0
    }
1334
54
}
1335
1336
// FIXME: Perhaps we could clear queued events as well?
1337
void ImGuiIO::ClearInputCharacters()
1338
5.81k
{
1339
5.81k
    InputQueueCharacters.resize(0);
1340
5.81k
}
1341
1342
// FIXME: Perhaps we could clear queued events as well?
1343
void ImGuiIO::ClearInputKeys()
1344
6.56k
{
1345
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1346
    memset(KeysDown, 0, sizeof(KeysDown));
1347
#endif
1348
925k
    for (int n = 0; n < IM_ARRAYSIZE(KeysData); n++)
1349
918k
    {
1350
918k
        KeysData[n].Down             = false;
1351
918k
        KeysData[n].DownDuration     = -1.0f;
1352
918k
        KeysData[n].DownDurationPrev = -1.0f;
1353
918k
    }
1354
6.56k
    KeyCtrl = KeyShift = KeyAlt = KeySuper = false;
1355
6.56k
    KeyMods = ImGuiMod_None;
1356
6.56k
    MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
1357
39.3k
    for (int n = 0; n < IM_ARRAYSIZE(MouseDown); n++)
1358
32.8k
    {
1359
32.8k
        MouseDown[n] = false;
1360
32.8k
        MouseDownDuration[n] = MouseDownDurationPrev[n] = -1.0f;
1361
32.8k
    }
1362
6.56k
    MouseWheel = MouseWheelH = 0.0f;
1363
6.56k
}
1364
1365
static ImGuiInputEvent* FindLatestInputEvent(ImGuiInputEventType type, int arg = -1)
1366
15.3k
{
1367
15.3k
    ImGuiContext& g = *GImGui;
1368
24.5k
    for (int n = g.InputEventsQueue.Size - 1; n >= 0; n--)
1369
13.3k
    {
1370
13.3k
        ImGuiInputEvent* e = &g.InputEventsQueue[n];
1371
13.3k
        if (e->Type != type)
1372
7.28k
            continue;
1373
6.05k
        if (type == ImGuiInputEventType_Key && e->Key.Key != arg)
1374
171
            continue;
1375
5.87k
        if (type == ImGuiInputEventType_MouseButton && e->MouseButton.Button != arg)
1376
1.72k
            continue;
1377
4.15k
        return e;
1378
5.87k
    }
1379
11.2k
    return NULL;
1380
15.3k
}
1381
1382
// Queue a new key down/up event.
1383
// - ImGuiKey key:       Translated key (as in, generally ImGuiKey_A matches the key end-user would use to emit an 'A' character)
1384
// - bool down:          Is the key down? use false to signify a key release.
1385
// - float analog_value: 0.0f..1.0f
1386
void ImGuiIO::AddKeyAnalogEvent(ImGuiKey key, bool down, float analog_value)
1387
1.61k
{
1388
    //if (e->Down) { IMGUI_DEBUG_LOG_IO("AddKeyEvent() Key='%s' %d, NativeKeycode = %d, NativeScancode = %d\n", ImGui::GetKeyName(e->Key), e->Down, e->NativeKeycode, e->NativeScancode); }
1389
1.61k
    if (key == ImGuiKey_None || !AppAcceptingEvents)
1390
0
        return;
1391
1.61k
    ImGuiContext& g = *GImGui;
1392
1.61k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1393
1.61k
    IM_ASSERT(ImGui::IsNamedKeyOrModKey(key)); // Backend needs to pass a valid ImGuiKey_ constant. 0..511 values are legacy native key codes which are not accepted by this API.
1394
1.61k
    IM_ASSERT(!ImGui::IsAliasKey(key)); // Backend cannot submit ImGuiKey_MouseXXX values they are automatically inferred from AddMouseXXX() events.
1395
1.61k
    IM_ASSERT(key != ImGuiMod_Shortcut); // We could easily support the translation here but it seems saner to not accept it (TestEngine perform a translation itself)
1396
1397
    // Verify that backend isn't mixing up using new io.AddKeyEvent() api and old io.KeysDown[] + io.KeyMap[] data.
1398
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1399
    IM_ASSERT((BackendUsingLegacyKeyArrays == -1 || BackendUsingLegacyKeyArrays == 0) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1400
    if (BackendUsingLegacyKeyArrays == -1)
1401
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
1402
            IM_ASSERT(KeyMap[n] == -1 && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
1403
    BackendUsingLegacyKeyArrays = 0;
1404
#endif
1405
1.61k
    if (ImGui::IsGamepadKey(key))
1406
73
        BackendUsingLegacyNavInputArray = false;
1407
1408
    // Filter duplicate (in particular: key mods and gamepad analog values are commonly spammed)
1409
1.61k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Key, (int)key);
1410
1.61k
    const ImGuiKeyData* key_data = ImGui::GetKeyData(key);
1411
1.61k
    const bool latest_key_down = latest_event ? latest_event->Key.Down : key_data->Down;
1412
1.61k
    const float latest_key_analog = latest_event ? latest_event->Key.AnalogValue : key_data->AnalogValue;
1413
1.61k
    if (latest_key_down == down && latest_key_analog == analog_value)
1414
203
        return;
1415
1416
    // Add event
1417
1.41k
    ImGuiInputEvent e;
1418
1.41k
    e.Type = ImGuiInputEventType_Key;
1419
1.41k
    e.Source = ImGui::IsGamepadKey(key) ? ImGuiInputSource_Gamepad : ImGuiInputSource_Keyboard;
1420
1.41k
    e.Key.Key = key;
1421
1.41k
    e.Key.Down = down;
1422
1.41k
    e.Key.AnalogValue = analog_value;
1423
1.41k
    g.InputEventsQueue.push_back(e);
1424
1.41k
}
1425
1426
void ImGuiIO::AddKeyEvent(ImGuiKey key, bool down)
1427
475
{
1428
475
    if (!AppAcceptingEvents)
1429
0
        return;
1430
475
    AddKeyAnalogEvent(key, down, down ? 1.0f : 0.0f);
1431
475
}
1432
1433
// [Optional] Call after AddKeyEvent().
1434
// Specify native keycode, scancode + Specify index for legacy <1.87 IsKeyXXX() functions with native indices.
1435
// If you are writing a backend in 2022 or don't use IsKeyXXX() with native values that are not ImGuiKey values, you can avoid calling this.
1436
void ImGuiIO::SetKeyEventNativeData(ImGuiKey key, int native_keycode, int native_scancode, int native_legacy_index)
1437
0
{
1438
0
    if (key == ImGuiKey_None)
1439
0
        return;
1440
0
    IM_ASSERT(ImGui::IsNamedKey(key)); // >= 512
1441
0
    IM_ASSERT(native_legacy_index == -1 || ImGui::IsLegacyKey((ImGuiKey)native_legacy_index)); // >= 0 && <= 511
1442
0
    IM_UNUSED(native_keycode);  // Yet unused
1443
0
    IM_UNUSED(native_scancode); // Yet unused
1444
1445
    // Build native->imgui map so old user code can still call key functions with native 0..511 values.
1446
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
1447
    const int legacy_key = (native_legacy_index != -1) ? native_legacy_index : native_keycode;
1448
    if (!ImGui::IsLegacyKey((ImGuiKey)legacy_key))
1449
        return;
1450
    KeyMap[legacy_key] = key;
1451
    KeyMap[key] = legacy_key;
1452
#else
1453
0
    IM_UNUSED(key);
1454
0
    IM_UNUSED(native_legacy_index);
1455
0
#endif
1456
0
}
1457
1458
// Set master flag for accepting key/mouse/text events (default to true). Useful if you have native dialog boxes that are interrupting your application loop/refresh, and you want to disable events being queued while your app is frozen.
1459
void ImGuiIO::SetAppAcceptingEvents(bool accepting_events)
1460
0
{
1461
0
    AppAcceptingEvents = accepting_events;
1462
0
}
1463
1464
// Queue a mouse move event
1465
void ImGuiIO::AddMousePosEvent(float x, float y)
1466
3.47k
{
1467
3.47k
    ImGuiContext& g = *GImGui;
1468
3.47k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1469
3.47k
    if (!AppAcceptingEvents)
1470
0
        return;
1471
1472
    // Apply same flooring as UpdateMouseInputs()
1473
3.47k
    ImVec2 pos((x > -FLT_MAX) ? ImFloorSigned(x) : x, (y > -FLT_MAX) ? ImFloorSigned(y) : y);
1474
1475
    // Filter duplicate
1476
3.47k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MousePos);
1477
3.47k
    const ImVec2 latest_pos = latest_event ? ImVec2(latest_event->MousePos.PosX, latest_event->MousePos.PosY) : g.IO.MousePos;
1478
3.47k
    if (latest_pos.x == pos.x && latest_pos.y == pos.y)
1479
1.17k
        return;
1480
1481
2.30k
    ImGuiInputEvent e;
1482
2.30k
    e.Type = ImGuiInputEventType_MousePos;
1483
2.30k
    e.Source = ImGuiInputSource_Mouse;
1484
2.30k
    e.MousePos.PosX = pos.x;
1485
2.30k
    e.MousePos.PosY = pos.y;
1486
2.30k
    g.InputEventsQueue.push_back(e);
1487
2.30k
}
1488
1489
void ImGuiIO::AddMouseButtonEvent(int mouse_button, bool down)
1490
8.51k
{
1491
8.51k
    ImGuiContext& g = *GImGui;
1492
8.51k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1493
8.51k
    IM_ASSERT(mouse_button >= 0 && mouse_button < ImGuiMouseButton_COUNT);
1494
8.51k
    if (!AppAcceptingEvents)
1495
0
        return;
1496
1497
    // Filter duplicate
1498
8.51k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseButton, (int)mouse_button);
1499
8.51k
    const bool latest_button_down = latest_event ? latest_event->MouseButton.Down : g.IO.MouseDown[mouse_button];
1500
8.51k
    if (latest_button_down == down)
1501
3.98k
        return;
1502
1503
4.52k
    ImGuiInputEvent e;
1504
4.52k
    e.Type = ImGuiInputEventType_MouseButton;
1505
4.52k
    e.Source = ImGuiInputSource_Mouse;
1506
4.52k
    e.MouseButton.Button = mouse_button;
1507
4.52k
    e.MouseButton.Down = down;
1508
4.52k
    g.InputEventsQueue.push_back(e);
1509
4.52k
}
1510
1511
// Queue a mouse wheel event (some mouse/API may only have a Y component)
1512
void ImGuiIO::AddMouseWheelEvent(float wheel_x, float wheel_y)
1513
1.41k
{
1514
1.41k
    ImGuiContext& g = *GImGui;
1515
1.41k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1516
1517
    // Filter duplicate (unlike most events, wheel values are relative and easy to filter)
1518
1.41k
    if (!AppAcceptingEvents || (wheel_x == 0.0f && wheel_y == 0.0f))
1519
361
        return;
1520
1521
1.05k
    ImGuiInputEvent e;
1522
1.05k
    e.Type = ImGuiInputEventType_MouseWheel;
1523
1.05k
    e.Source = ImGuiInputSource_Mouse;
1524
1.05k
    e.MouseWheel.WheelX = wheel_x;
1525
1.05k
    e.MouseWheel.WheelY = wheel_y;
1526
1.05k
    g.InputEventsQueue.push_back(e);
1527
1.05k
}
1528
1529
void ImGuiIO::AddMouseViewportEvent(ImGuiID viewport_id)
1530
0
{
1531
0
    ImGuiContext& g = *GImGui;
1532
0
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1533
0
    IM_ASSERT(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport);
1534
0
    if (!AppAcceptingEvents)
1535
0
        return;
1536
1537
    // Filter duplicate
1538
0
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_MouseViewport);
1539
0
    const ImGuiID latest_viewport_id = latest_event ? latest_event->MouseViewport.HoveredViewportID : g.IO.MouseHoveredViewport;
1540
0
    if (latest_viewport_id == viewport_id)
1541
0
        return;
1542
1543
0
    ImGuiInputEvent e;
1544
0
    e.Type = ImGuiInputEventType_MouseViewport;
1545
0
    e.Source = ImGuiInputSource_Mouse;
1546
0
    e.MouseViewport.HoveredViewportID = viewport_id;
1547
0
    g.InputEventsQueue.push_back(e);
1548
0
}
1549
1550
void ImGuiIO::AddFocusEvent(bool focused)
1551
1.77k
{
1552
1.77k
    ImGuiContext& g = *GImGui;
1553
1.77k
    IM_ASSERT(&g.IO == this && "Can only add events to current context.");
1554
1555
    // Filter duplicate
1556
1.77k
    const ImGuiInputEvent* latest_event = FindLatestInputEvent(ImGuiInputEventType_Focus);
1557
1.77k
    const bool latest_focused = latest_event ? latest_event->AppFocused.Focused : !g.IO.AppFocusLost;
1558
1.77k
    if (latest_focused == focused)
1559
331
        return;
1560
1561
1.44k
    ImGuiInputEvent e;
1562
1.44k
    e.Type = ImGuiInputEventType_Focus;
1563
1.44k
    e.AppFocused.Focused = focused;
1564
1.44k
    g.InputEventsQueue.push_back(e);
1565
1.44k
}
1566
1567
//-----------------------------------------------------------------------------
1568
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
1569
//-----------------------------------------------------------------------------
1570
1571
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
1572
0
{
1573
0
    IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
1574
0
    ImVec2 p_last = p1;
1575
0
    ImVec2 p_closest;
1576
0
    float p_closest_dist2 = FLT_MAX;
1577
0
    float t_step = 1.0f / (float)num_segments;
1578
0
    for (int i_step = 1; i_step <= num_segments; i_step++)
1579
0
    {
1580
0
        ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
1581
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1582
0
        float dist2 = ImLengthSqr(p - p_line);
1583
0
        if (dist2 < p_closest_dist2)
1584
0
        {
1585
0
            p_closest = p_line;
1586
0
            p_closest_dist2 = dist2;
1587
0
        }
1588
0
        p_last = p_current;
1589
0
    }
1590
0
    return p_closest;
1591
0
}
1592
1593
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
1594
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
1595
0
{
1596
0
    float dx = x4 - x1;
1597
0
    float dy = y4 - y1;
1598
0
    float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
1599
0
    float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
1600
0
    d2 = (d2 >= 0) ? d2 : -d2;
1601
0
    d3 = (d3 >= 0) ? d3 : -d3;
1602
0
    if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
1603
0
    {
1604
0
        ImVec2 p_current(x4, y4);
1605
0
        ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
1606
0
        float dist2 = ImLengthSqr(p - p_line);
1607
0
        if (dist2 < p_closest_dist2)
1608
0
        {
1609
0
            p_closest = p_line;
1610
0
            p_closest_dist2 = dist2;
1611
0
        }
1612
0
        p_last = p_current;
1613
0
    }
1614
0
    else if (level < 10)
1615
0
    {
1616
0
        float x12 = (x1 + x2)*0.5f,       y12 = (y1 + y2)*0.5f;
1617
0
        float x23 = (x2 + x3)*0.5f,       y23 = (y2 + y3)*0.5f;
1618
0
        float x34 = (x3 + x4)*0.5f,       y34 = (y3 + y4)*0.5f;
1619
0
        float x123 = (x12 + x23)*0.5f,    y123 = (y12 + y23)*0.5f;
1620
0
        float x234 = (x23 + x34)*0.5f,    y234 = (y23 + y34)*0.5f;
1621
0
        float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
1622
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
1623
0
        ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
1624
0
    }
1625
0
}
1626
1627
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
1628
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
1629
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
1630
0
{
1631
0
    IM_ASSERT(tess_tol > 0.0f);
1632
0
    ImVec2 p_last = p1;
1633
0
    ImVec2 p_closest;
1634
0
    float p_closest_dist2 = FLT_MAX;
1635
0
    ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
1636
0
    return p_closest;
1637
0
}
1638
1639
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
1640
0
{
1641
0
    ImVec2 ap = p - a;
1642
0
    ImVec2 ab_dir = b - a;
1643
0
    float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
1644
0
    if (dot < 0.0f)
1645
0
        return a;
1646
0
    float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
1647
0
    if (dot > ab_len_sqr)
1648
0
        return b;
1649
0
    return a + ab_dir * dot / ab_len_sqr;
1650
0
}
1651
1652
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1653
0
{
1654
0
    bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
1655
0
    bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
1656
0
    bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
1657
0
    return ((b1 == b2) && (b2 == b3));
1658
0
}
1659
1660
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
1661
0
{
1662
0
    ImVec2 v0 = b - a;
1663
0
    ImVec2 v1 = c - a;
1664
0
    ImVec2 v2 = p - a;
1665
0
    const float denom = v0.x * v1.y - v1.x * v0.y;
1666
0
    out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
1667
0
    out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
1668
0
    out_u = 1.0f - out_v - out_w;
1669
0
}
1670
1671
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
1672
0
{
1673
0
    ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
1674
0
    ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
1675
0
    ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
1676
0
    float dist2_ab = ImLengthSqr(p - proj_ab);
1677
0
    float dist2_bc = ImLengthSqr(p - proj_bc);
1678
0
    float dist2_ca = ImLengthSqr(p - proj_ca);
1679
0
    float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
1680
0
    if (m == dist2_ab)
1681
0
        return proj_ab;
1682
0
    if (m == dist2_bc)
1683
0
        return proj_bc;
1684
0
    return proj_ca;
1685
0
}
1686
1687
//-----------------------------------------------------------------------------
1688
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
1689
//-----------------------------------------------------------------------------
1690
1691
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
1692
int ImStricmp(const char* str1, const char* str2)
1693
0
{
1694
0
    int d;
1695
0
    while ((d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; }
1696
0
    return d;
1697
0
}
1698
1699
int ImStrnicmp(const char* str1, const char* str2, size_t count)
1700
0
{
1701
0
    int d = 0;
1702
0
    while (count > 0 && (d = ImToUpper(*str2) - ImToUpper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
1703
0
    return d;
1704
0
}
1705
1706
void ImStrncpy(char* dst, const char* src, size_t count)
1707
75
{
1708
75
    if (count < 1)
1709
0
        return;
1710
75
    if (count > 1)
1711
75
        strncpy(dst, src, count - 1);
1712
75
    dst[count - 1] = 0;
1713
75
}
1714
1715
char* ImStrdup(const char* str)
1716
3
{
1717
3
    size_t len = strlen(str);
1718
3
    void* buf = IM_ALLOC(len + 1);
1719
3
    return (char*)memcpy(buf, (const void*)str, len + 1);
1720
3
}
1721
1722
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
1723
0
{
1724
0
    size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
1725
0
    size_t src_size = strlen(src) + 1;
1726
0
    if (dst_buf_size < src_size)
1727
0
    {
1728
0
        IM_FREE(dst);
1729
0
        dst = (char*)IM_ALLOC(src_size);
1730
0
        if (p_dst_size)
1731
0
            *p_dst_size = src_size;
1732
0
    }
1733
0
    return (char*)memcpy(dst, (const void*)src, src_size);
1734
0
}
1735
1736
const char* ImStrchrRange(const char* str, const char* str_end, char c)
1737
0
{
1738
0
    const char* p = (const char*)memchr(str, (int)c, str_end - str);
1739
0
    return p;
1740
0
}
1741
1742
int ImStrlenW(const ImWchar* str)
1743
0
{
1744
    //return (int)wcslen((const wchar_t*)str);  // FIXME-OPT: Could use this when wchar_t are 16-bit
1745
0
    int n = 0;
1746
0
    while (*str++) n++;
1747
0
    return n;
1748
0
}
1749
1750
// Find end-of-line. Return pointer will point to either first \n, either str_end.
1751
const char* ImStreolRange(const char* str, const char* str_end)
1752
0
{
1753
0
    const char* p = (const char*)memchr(str, '\n', str_end - str);
1754
0
    return p ? p : str_end;
1755
0
}
1756
1757
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
1758
0
{
1759
0
    while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
1760
0
        buf_mid_line--;
1761
0
    return buf_mid_line;
1762
0
}
1763
1764
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
1765
0
{
1766
0
    if (!needle_end)
1767
0
        needle_end = needle + strlen(needle);
1768
1769
0
    const char un0 = (char)ImToUpper(*needle);
1770
0
    while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
1771
0
    {
1772
0
        if (ImToUpper(*haystack) == un0)
1773
0
        {
1774
0
            const char* b = needle + 1;
1775
0
            for (const char* a = haystack + 1; b < needle_end; a++, b++)
1776
0
                if (ImToUpper(*a) != ImToUpper(*b))
1777
0
                    break;
1778
0
            if (b == needle_end)
1779
0
                return haystack;
1780
0
        }
1781
0
        haystack++;
1782
0
    }
1783
0
    return NULL;
1784
0
}
1785
1786
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
1787
void ImStrTrimBlanks(char* buf)
1788
0
{
1789
0
    char* p = buf;
1790
0
    while (p[0] == ' ' || p[0] == '\t')     // Leading blanks
1791
0
        p++;
1792
0
    char* p_start = p;
1793
0
    while (*p != 0)                         // Find end of string
1794
0
        p++;
1795
0
    while (p > p_start && (p[-1] == ' ' || p[-1] == '\t'))  // Trailing blanks
1796
0
        p--;
1797
0
    if (p_start != buf)                     // Copy memory if we had leading blanks
1798
0
        memmove(buf, p_start, p - p_start);
1799
0
    buf[p - p_start] = 0;                   // Zero terminate
1800
0
}
1801
1802
const char* ImStrSkipBlank(const char* str)
1803
0
{
1804
0
    while (str[0] == ' ' || str[0] == '\t')
1805
0
        str++;
1806
0
    return str;
1807
0
}
1808
1809
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
1810
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
1811
// B) When buf==NULL vsnprintf() will return the output size.
1812
#ifndef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1813
1814
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
1815
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1816
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
1817
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
1818
#ifdef IMGUI_USE_STB_SPRINTF
1819
#define STB_SPRINTF_IMPLEMENTATION
1820
#ifdef IMGUI_STB_SPRINTF_FILENAME
1821
#include IMGUI_STB_SPRINTF_FILENAME
1822
#else
1823
#include "stb_sprintf.h"
1824
#endif
1825
#endif
1826
1827
#if defined(_MSC_VER) && !defined(vsnprintf)
1828
#define vsnprintf _vsnprintf
1829
#endif
1830
1831
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
1832
1
{
1833
1
    va_list args;
1834
1
    va_start(args, fmt);
1835
#ifdef IMGUI_USE_STB_SPRINTF
1836
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1837
#else
1838
1
    int w = vsnprintf(buf, buf_size, fmt, args);
1839
1
#endif
1840
1
    va_end(args);
1841
1
    if (buf == NULL)
1842
0
        return w;
1843
1
    if (w == -1 || w >= (int)buf_size)
1844
0
        w = (int)buf_size - 1;
1845
1
    buf[w] = 0;
1846
1
    return w;
1847
1
}
1848
1849
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
1850
3.02k
{
1851
#ifdef IMGUI_USE_STB_SPRINTF
1852
    int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
1853
#else
1854
3.02k
    int w = vsnprintf(buf, buf_size, fmt, args);
1855
3.02k
#endif
1856
3.02k
    if (buf == NULL)
1857
0
        return w;
1858
3.02k
    if (w == -1 || w >= (int)buf_size)
1859
0
        w = (int)buf_size - 1;
1860
3.02k
    buf[w] = 0;
1861
3.02k
    return w;
1862
3.02k
}
1863
#endif // #ifdef IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
1864
1865
void ImFormatStringToTempBuffer(const char** out_buf, const char** out_buf_end, const char* fmt, ...)
1866
3.02k
{
1867
3.02k
    ImGuiContext& g = *GImGui;
1868
3.02k
    va_list args;
1869
3.02k
    va_start(args, fmt);
1870
3.02k
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1871
0
    {
1872
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1873
0
        *out_buf = buf;
1874
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1875
0
    }
1876
3.02k
    else
1877
3.02k
    {
1878
3.02k
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1879
3.02k
        *out_buf = g.TempBuffer.Data;
1880
3.02k
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1881
3.02k
    }
1882
3.02k
    va_end(args);
1883
3.02k
}
1884
1885
void ImFormatStringToTempBufferV(const char** out_buf, const char** out_buf_end, const char* fmt, va_list args)
1886
0
{
1887
0
    ImGuiContext& g = *GImGui;
1888
0
    if (fmt[0] == '%' && fmt[1] == 's' && fmt[2] == 0)
1889
0
    {
1890
0
        const char* buf = va_arg(args, const char*); // Skip formatting when using "%s"
1891
0
        *out_buf = buf;
1892
0
        if (out_buf_end) { *out_buf_end = buf + strlen(buf); }
1893
0
    }
1894
0
    else
1895
0
    {
1896
0
        int buf_len = ImFormatStringV(g.TempBuffer.Data, g.TempBuffer.Size, fmt, args);
1897
0
        *out_buf = g.TempBuffer.Data;
1898
0
        if (out_buf_end) { *out_buf_end = g.TempBuffer.Data + buf_len; }
1899
0
    }
1900
0
}
1901
1902
// CRC32 needs a 1KB lookup table (not cache friendly)
1903
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
1904
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
1905
static const ImU32 GCrc32LookupTable[256] =
1906
{
1907
    0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
1908
    0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
1909
    0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
1910
    0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
1911
    0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
1912
    0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
1913
    0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
1914
    0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
1915
    0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
1916
    0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
1917
    0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
1918
    0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
1919
    0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
1920
    0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
1921
    0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
1922
    0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
1923
};
1924
1925
// Known size hash
1926
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
1927
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1928
ImGuiID ImHashData(const void* data_p, size_t data_size, ImGuiID seed)
1929
3.02k
{
1930
3.02k
    ImU32 crc = ~seed;
1931
3.02k
    const unsigned char* data = (const unsigned char*)data_p;
1932
3.02k
    const ImU32* crc32_lut = GCrc32LookupTable;
1933
15.1k
    while (data_size-- != 0)
1934
12.0k
        crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
1935
3.02k
    return ~crc;
1936
3.02k
}
1937
1938
// Zero-terminated string hash, with support for ### to reset back to seed value
1939
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
1940
// Because this syntax is rarely used we are optimizing for the common case.
1941
// - If we reach ### in the string we discard the hash so far and reset to the seed.
1942
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
1943
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
1944
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImGuiID seed)
1945
151k
{
1946
151k
    seed = ~seed;
1947
151k
    ImU32 crc = seed;
1948
151k
    const unsigned char* data = (const unsigned char*)data_p;
1949
151k
    const ImU32* crc32_lut = GCrc32LookupTable;
1950
151k
    if (data_size != 0)
1951
0
    {
1952
0
        while (data_size-- != 0)
1953
0
        {
1954
0
            unsigned char c = *data++;
1955
0
            if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
1956
0
                crc = seed;
1957
0
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1958
0
        }
1959
0
    }
1960
151k
    else
1961
151k
    {
1962
1.82M
        while (unsigned char c = *data++)
1963
1.66M
        {
1964
1.66M
            if (c == '#' && data[0] == '#' && data[1] == '#')
1965
0
                crc = seed;
1966
1.66M
            crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
1967
1.66M
        }
1968
151k
    }
1969
151k
    return ~crc;
1970
151k
}
1971
1972
//-----------------------------------------------------------------------------
1973
// [SECTION] MISC HELPERS/UTILITIES (File functions)
1974
//-----------------------------------------------------------------------------
1975
1976
// Default file functions
1977
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
1978
1979
ImFileHandle ImFileOpen(const char* filename, const char* mode)
1980
0
{
1981
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
1982
    // We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
1983
    // Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
1984
    const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
1985
    const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
1986
    ImVector<wchar_t> buf;
1987
    buf.resize(filename_wsize + mode_wsize);
1988
    ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
1989
    ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
1990
    return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
1991
#else
1992
0
    return fopen(filename, mode);
1993
0
#endif
1994
0
}
1995
1996
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
1997
0
bool    ImFileClose(ImFileHandle f)     { return fclose(f) == 0; }
1998
0
ImU64   ImFileGetSize(ImFileHandle f)   { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
1999
0
ImU64   ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f)           { return fread(data, (size_t)sz, (size_t)count, f); }
2000
0
ImU64   ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f)    { return fwrite(data, (size_t)sz, (size_t)count, f); }
2001
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
2002
2003
// Helper: Load file content into memory
2004
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
2005
// This can't really be used with "rt" because fseek size won't match read size.
2006
void*   ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
2007
0
{
2008
0
    IM_ASSERT(filename && mode);
2009
0
    if (out_file_size)
2010
0
        *out_file_size = 0;
2011
2012
0
    ImFileHandle f;
2013
0
    if ((f = ImFileOpen(filename, mode)) == NULL)
2014
0
        return NULL;
2015
2016
0
    size_t file_size = (size_t)ImFileGetSize(f);
2017
0
    if (file_size == (size_t)-1)
2018
0
    {
2019
0
        ImFileClose(f);
2020
0
        return NULL;
2021
0
    }
2022
2023
0
    void* file_data = IM_ALLOC(file_size + padding_bytes);
2024
0
    if (file_data == NULL)
2025
0
    {
2026
0
        ImFileClose(f);
2027
0
        return NULL;
2028
0
    }
2029
0
    if (ImFileRead(file_data, 1, file_size, f) != file_size)
2030
0
    {
2031
0
        ImFileClose(f);
2032
0
        IM_FREE(file_data);
2033
0
        return NULL;
2034
0
    }
2035
0
    if (padding_bytes > 0)
2036
0
        memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
2037
2038
0
    ImFileClose(f);
2039
0
    if (out_file_size)
2040
0
        *out_file_size = file_size;
2041
2042
0
    return file_data;
2043
0
}
2044
2045
//-----------------------------------------------------------------------------
2046
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
2047
//-----------------------------------------------------------------------------
2048
2049
IM_MSVC_RUNTIME_CHECKS_OFF
2050
2051
// Convert UTF-8 to 32-bit character, process single character input.
2052
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
2053
// We handle UTF-8 decoding error by skipping forward.
2054
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
2055
3.55k
{
2056
3.55k
    static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
2057
3.55k
    static const int masks[]  = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
2058
3.55k
    static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
2059
3.55k
    static const int shiftc[] = { 0, 18, 12, 6, 0 };
2060
3.55k
    static const int shifte[] = { 0, 6, 4, 2, 0 };
2061
3.55k
    int len = lengths[*(const unsigned char*)in_text >> 3];
2062
3.55k
    int wanted = len + (len ? 0 : 1);
2063
2064
3.55k
    if (in_text_end == NULL)
2065
0
        in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
2066
2067
    // Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
2068
    // so it is fast even with excessive branching.
2069
3.55k
    unsigned char s[4];
2070
3.55k
    s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
2071
3.55k
    s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
2072
3.55k
    s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
2073
3.55k
    s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
2074
2075
    // Assume a four-byte character and load four bytes. Unused bits are shifted out.
2076
3.55k
    *out_char  = (uint32_t)(s[0] & masks[len]) << 18;
2077
3.55k
    *out_char |= (uint32_t)(s[1] & 0x3f) << 12;
2078
3.55k
    *out_char |= (uint32_t)(s[2] & 0x3f) <<  6;
2079
3.55k
    *out_char |= (uint32_t)(s[3] & 0x3f) <<  0;
2080
3.55k
    *out_char >>= shiftc[len];
2081
2082
    // Accumulate the various error conditions.
2083
3.55k
    int e = 0;
2084
3.55k
    e  = (*out_char < mins[len]) << 6; // non-canonical encoding
2085
3.55k
    e |= ((*out_char >> 11) == 0x1b) << 7;  // surrogate half?
2086
3.55k
    e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8;  // out of range?
2087
3.55k
    e |= (s[1] & 0xc0) >> 2;
2088
3.55k
    e |= (s[2] & 0xc0) >> 4;
2089
3.55k
    e |= (s[3]       ) >> 6;
2090
3.55k
    e ^= 0x2a; // top two bits of each tail byte correct?
2091
3.55k
    e >>= shifte[len];
2092
2093
3.55k
    if (e)
2094
117
    {
2095
        // No bytes are consumed when *in_text == 0 || in_text == in_text_end.
2096
        // One byte is consumed in case of invalid first byte of in_text.
2097
        // All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
2098
        // Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
2099
117
        wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
2100
117
        *out_char = IM_UNICODE_CODEPOINT_INVALID;
2101
117
    }
2102
2103
3.55k
    return wanted;
2104
3.55k
}
2105
2106
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
2107
0
{
2108
0
    ImWchar* buf_out = buf;
2109
0
    ImWchar* buf_end = buf + buf_size;
2110
0
    while (buf_out < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2111
0
    {
2112
0
        unsigned int c;
2113
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2114
0
        *buf_out++ = (ImWchar)c;
2115
0
    }
2116
0
    *buf_out = 0;
2117
0
    if (in_text_remaining)
2118
0
        *in_text_remaining = in_text;
2119
0
    return (int)(buf_out - buf);
2120
0
}
2121
2122
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
2123
0
{
2124
0
    int char_count = 0;
2125
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2126
0
    {
2127
0
        unsigned int c;
2128
0
        in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
2129
0
        char_count++;
2130
0
    }
2131
0
    return char_count;
2132
0
}
2133
2134
// Based on stb_to_utf8() from github.com/nothings/stb/
2135
static inline int ImTextCharToUtf8_inline(char* buf, int buf_size, unsigned int c)
2136
0
{
2137
0
    if (c < 0x80)
2138
0
    {
2139
0
        buf[0] = (char)c;
2140
0
        return 1;
2141
0
    }
2142
0
    if (c < 0x800)
2143
0
    {
2144
0
        if (buf_size < 2) return 0;
2145
0
        buf[0] = (char)(0xc0 + (c >> 6));
2146
0
        buf[1] = (char)(0x80 + (c & 0x3f));
2147
0
        return 2;
2148
0
    }
2149
0
    if (c < 0x10000)
2150
0
    {
2151
0
        if (buf_size < 3) return 0;
2152
0
        buf[0] = (char)(0xe0 + (c >> 12));
2153
0
        buf[1] = (char)(0x80 + ((c >> 6) & 0x3f));
2154
0
        buf[2] = (char)(0x80 + ((c ) & 0x3f));
2155
0
        return 3;
2156
0
    }
2157
0
    if (c <= 0x10FFFF)
2158
0
    {
2159
0
        if (buf_size < 4) return 0;
2160
0
        buf[0] = (char)(0xf0 + (c >> 18));
2161
0
        buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
2162
0
        buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
2163
0
        buf[3] = (char)(0x80 + ((c ) & 0x3f));
2164
0
        return 4;
2165
0
    }
2166
    // Invalid code point, the max unicode is 0x10FFFF
2167
0
    return 0;
2168
0
}
2169
2170
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
2171
0
{
2172
0
    int count = ImTextCharToUtf8_inline(out_buf, 5, c);
2173
0
    out_buf[count] = 0;
2174
0
    return out_buf;
2175
0
}
2176
2177
// Not optimal but we very rarely use this function.
2178
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
2179
0
{
2180
0
    unsigned int unused = 0;
2181
0
    return ImTextCharFromUtf8(&unused, in_text, in_text_end);
2182
0
}
2183
2184
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
2185
0
{
2186
0
    if (c < 0x80) return 1;
2187
0
    if (c < 0x800) return 2;
2188
0
    if (c < 0x10000) return 3;
2189
0
    if (c <= 0x10FFFF) return 4;
2190
0
    return 3;
2191
0
}
2192
2193
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
2194
0
{
2195
0
    char* buf_p = out_buf;
2196
0
    const char* buf_end = out_buf + out_buf_size;
2197
0
    while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
2198
0
    {
2199
0
        unsigned int c = (unsigned int)(*in_text++);
2200
0
        if (c < 0x80)
2201
0
            *buf_p++ = (char)c;
2202
0
        else
2203
0
            buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
2204
0
    }
2205
0
    *buf_p = 0;
2206
0
    return (int)(buf_p - out_buf);
2207
0
}
2208
2209
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
2210
0
{
2211
0
    int bytes_count = 0;
2212
0
    while ((!in_text_end || in_text < in_text_end) && *in_text)
2213
0
    {
2214
0
        unsigned int c = (unsigned int)(*in_text++);
2215
0
        if (c < 0x80)
2216
0
            bytes_count++;
2217
0
        else
2218
0
            bytes_count += ImTextCountUtf8BytesFromChar(c);
2219
0
    }
2220
0
    return bytes_count;
2221
0
}
2222
IM_MSVC_RUNTIME_CHECKS_RESTORE
2223
2224
//-----------------------------------------------------------------------------
2225
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
2226
// Note: The Convert functions are early design which are not consistent with other API.
2227
//-----------------------------------------------------------------------------
2228
2229
IMGUI_API ImU32 ImAlphaBlendColors(ImU32 col_a, ImU32 col_b)
2230
0
{
2231
0
    float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
2232
0
    int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
2233
0
    int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
2234
0
    int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
2235
0
    return IM_COL32(r, g, b, 0xFF);
2236
0
}
2237
2238
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
2239
115k
{
2240
115k
    float s = 1.0f / 255.0f;
2241
115k
    return ImVec4(
2242
115k
        ((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
2243
115k
        ((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
2244
115k
        ((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
2245
115k
        ((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
2246
115k
}
2247
2248
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
2249
509k
{
2250
509k
    ImU32 out;
2251
509k
    out  = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
2252
509k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
2253
509k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
2254
509k
    out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
2255
509k
    return out;
2256
509k
}
2257
2258
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
2259
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
2260
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
2261
0
{
2262
0
    float K = 0.f;
2263
0
    if (g < b)
2264
0
    {
2265
0
        ImSwap(g, b);
2266
0
        K = -1.f;
2267
0
    }
2268
0
    if (r < g)
2269
0
    {
2270
0
        ImSwap(r, g);
2271
0
        K = -2.f / 6.f - K;
2272
0
    }
2273
2274
0
    const float chroma = r - (g < b ? g : b);
2275
0
    out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
2276
0
    out_s = chroma / (r + 1e-20f);
2277
0
    out_v = r;
2278
0
}
2279
2280
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
2281
// also http://en.wikipedia.org/wiki/HSL_and_HSV
2282
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
2283
0
{
2284
0
    if (s == 0.0f)
2285
0
    {
2286
        // gray
2287
0
        out_r = out_g = out_b = v;
2288
0
        return;
2289
0
    }
2290
2291
0
    h = ImFmod(h, 1.0f) / (60.0f / 360.0f);
2292
0
    int   i = (int)h;
2293
0
    float f = h - (float)i;
2294
0
    float p = v * (1.0f - s);
2295
0
    float q = v * (1.0f - s * f);
2296
0
    float t = v * (1.0f - s * (1.0f - f));
2297
2298
0
    switch (i)
2299
0
    {
2300
0
    case 0: out_r = v; out_g = t; out_b = p; break;
2301
0
    case 1: out_r = q; out_g = v; out_b = p; break;
2302
0
    case 2: out_r = p; out_g = v; out_b = t; break;
2303
0
    case 3: out_r = p; out_g = q; out_b = v; break;
2304
0
    case 4: out_r = t; out_g = p; out_b = v; break;
2305
0
    case 5: default: out_r = v; out_g = p; out_b = q; break;
2306
0
    }
2307
0
}
2308
2309
//-----------------------------------------------------------------------------
2310
// [SECTION] ImGuiStorage
2311
// Helper: Key->value storage
2312
//-----------------------------------------------------------------------------
2313
2314
// std::lower_bound but without the bullshit
2315
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
2316
71.9k
{
2317
71.9k
    ImGuiStorage::ImGuiStoragePair* first = data.Data;
2318
71.9k
    ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
2319
71.9k
    size_t count = (size_t)(last - first);
2320
215k
    while (count > 0)
2321
143k
    {
2322
143k
        size_t count2 = count >> 1;
2323
143k
        ImGuiStorage::ImGuiStoragePair* mid = first + count2;
2324
143k
        if (mid->key < key)
2325
37.4k
        {
2326
37.4k
            first = ++mid;
2327
37.4k
            count -= count2 + 1;
2328
37.4k
        }
2329
106k
        else
2330
106k
        {
2331
106k
            count = count2;
2332
106k
        }
2333
143k
    }
2334
71.9k
    return first;
2335
71.9k
}
2336
2337
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
2338
void ImGuiStorage::BuildSortByKey()
2339
0
{
2340
0
    struct StaticFunc
2341
0
    {
2342
0
        static int IMGUI_CDECL PairComparerByID(const void* lhs, const void* rhs)
2343
0
        {
2344
            // We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
2345
0
            if (((const ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
2346
0
            if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
2347
0
            return 0;
2348
0
        }
2349
0
    };
2350
0
    ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairComparerByID);
2351
0
}
2352
2353
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
2354
0
{
2355
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2356
0
    if (it == Data.end() || it->key != key)
2357
0
        return default_val;
2358
0
    return it->val_i;
2359
0
}
2360
2361
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
2362
0
{
2363
0
    return GetInt(key, default_val ? 1 : 0) != 0;
2364
0
}
2365
2366
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
2367
0
{
2368
0
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2369
0
    if (it == Data.end() || it->key != key)
2370
0
        return default_val;
2371
0
    return it->val_f;
2372
0
}
2373
2374
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
2375
71.9k
{
2376
71.9k
    ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
2377
71.9k
    if (it == Data.end() || it->key != key)
2378
3
        return NULL;
2379
71.9k
    return it->val_p;
2380
71.9k
}
2381
2382
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
2383
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
2384
0
{
2385
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2386
0
    if (it == Data.end() || it->key != key)
2387
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2388
0
    return &it->val_i;
2389
0
}
2390
2391
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
2392
0
{
2393
0
    return (bool*)GetIntRef(key, default_val ? 1 : 0);
2394
0
}
2395
2396
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
2397
0
{
2398
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2399
0
    if (it == Data.end() || it->key != key)
2400
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2401
0
    return &it->val_f;
2402
0
}
2403
2404
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
2405
0
{
2406
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2407
0
    if (it == Data.end() || it->key != key)
2408
0
        it = Data.insert(it, ImGuiStoragePair(key, default_val));
2409
0
    return &it->val_p;
2410
0
}
2411
2412
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
2413
void ImGuiStorage::SetInt(ImGuiID key, int val)
2414
0
{
2415
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2416
0
    if (it == Data.end() || it->key != key)
2417
0
    {
2418
0
        Data.insert(it, ImGuiStoragePair(key, val));
2419
0
        return;
2420
0
    }
2421
0
    it->val_i = val;
2422
0
}
2423
2424
void ImGuiStorage::SetBool(ImGuiID key, bool val)
2425
0
{
2426
0
    SetInt(key, val ? 1 : 0);
2427
0
}
2428
2429
void ImGuiStorage::SetFloat(ImGuiID key, float val)
2430
0
{
2431
0
    ImGuiStoragePair* it = LowerBound(Data, key);
2432
0
    if (it == Data.end() || it->key != key)
2433
0
    {
2434
0
        Data.insert(it, ImGuiStoragePair(key, val));
2435
0
        return;
2436
0
    }
2437
0
    it->val_f = val;
2438
0
}
2439
2440
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
2441
3
{
2442
3
    ImGuiStoragePair* it = LowerBound(Data, key);
2443
3
    if (it == Data.end() || it->key != key)
2444
3
    {
2445
3
        Data.insert(it, ImGuiStoragePair(key, val));
2446
3
        return;
2447
3
    }
2448
0
    it->val_p = val;
2449
0
}
2450
2451
void ImGuiStorage::SetAllInt(int v)
2452
0
{
2453
0
    for (int i = 0; i < Data.Size; i++)
2454
0
        Data[i].val_i = v;
2455
0
}
2456
2457
//-----------------------------------------------------------------------------
2458
// [SECTION] ImGuiTextFilter
2459
//-----------------------------------------------------------------------------
2460
2461
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
2462
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) //-V1077
2463
0
{
2464
0
    InputBuf[0] = 0;
2465
0
    CountGrep = 0;
2466
0
    if (default_filter)
2467
0
    {
2468
0
        ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
2469
0
        Build();
2470
0
    }
2471
0
}
2472
2473
bool ImGuiTextFilter::Draw(const char* label, float width)
2474
0
{
2475
0
    if (width != 0.0f)
2476
0
        ImGui::SetNextItemWidth(width);
2477
0
    bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
2478
0
    if (value_changed)
2479
0
        Build();
2480
0
    return value_changed;
2481
0
}
2482
2483
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
2484
0
{
2485
0
    out->resize(0);
2486
0
    const char* wb = b;
2487
0
    const char* we = wb;
2488
0
    while (we < e)
2489
0
    {
2490
0
        if (*we == separator)
2491
0
        {
2492
0
            out->push_back(ImGuiTextRange(wb, we));
2493
0
            wb = we + 1;
2494
0
        }
2495
0
        we++;
2496
0
    }
2497
0
    if (wb != we)
2498
0
        out->push_back(ImGuiTextRange(wb, we));
2499
0
}
2500
2501
void ImGuiTextFilter::Build()
2502
0
{
2503
0
    Filters.resize(0);
2504
0
    ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
2505
0
    input_range.split(',', &Filters);
2506
2507
0
    CountGrep = 0;
2508
0
    for (int i = 0; i != Filters.Size; i++)
2509
0
    {
2510
0
        ImGuiTextRange& f = Filters[i];
2511
0
        while (f.b < f.e && ImCharIsBlankA(f.b[0]))
2512
0
            f.b++;
2513
0
        while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
2514
0
            f.e--;
2515
0
        if (f.empty())
2516
0
            continue;
2517
0
        if (Filters[i].b[0] != '-')
2518
0
            CountGrep += 1;
2519
0
    }
2520
0
}
2521
2522
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
2523
0
{
2524
0
    if (Filters.empty())
2525
0
        return true;
2526
2527
0
    if (text == NULL)
2528
0
        text = "";
2529
2530
0
    for (int i = 0; i != Filters.Size; i++)
2531
0
    {
2532
0
        const ImGuiTextRange& f = Filters[i];
2533
0
        if (f.empty())
2534
0
            continue;
2535
0
        if (f.b[0] == '-')
2536
0
        {
2537
            // Subtract
2538
0
            if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
2539
0
                return false;
2540
0
        }
2541
0
        else
2542
0
        {
2543
            // Grep
2544
0
            if (ImStristr(text, text_end, f.b, f.e) != NULL)
2545
0
                return true;
2546
0
        }
2547
0
    }
2548
2549
    // Implicit * grep
2550
0
    if (CountGrep == 0)
2551
0
        return true;
2552
2553
0
    return false;
2554
0
}
2555
2556
//-----------------------------------------------------------------------------
2557
// [SECTION] ImGuiTextBuffer, ImGuiTextIndex
2558
//-----------------------------------------------------------------------------
2559
2560
// On some platform vsnprintf() takes va_list by reference and modifies it.
2561
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
2562
#ifndef va_copy
2563
#if defined(__GNUC__) || defined(__clang__)
2564
#define va_copy(dest, src) __builtin_va_copy(dest, src)
2565
#else
2566
#define va_copy(dest, src) (dest = src)
2567
#endif
2568
#endif
2569
2570
char ImGuiTextBuffer::EmptyString[1] = { 0 };
2571
2572
void ImGuiTextBuffer::append(const char* str, const char* str_end)
2573
0
{
2574
0
    int len = str_end ? (int)(str_end - str) : (int)strlen(str);
2575
2576
    // Add zero-terminator the first time
2577
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2578
0
    const int needed_sz = write_off + len;
2579
0
    if (write_off + len >= Buf.Capacity)
2580
0
    {
2581
0
        int new_capacity = Buf.Capacity * 2;
2582
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2583
0
    }
2584
2585
0
    Buf.resize(needed_sz);
2586
0
    memcpy(&Buf[write_off - 1], str, (size_t)len);
2587
0
    Buf[write_off - 1 + len] = 0;
2588
0
}
2589
2590
void ImGuiTextBuffer::appendf(const char* fmt, ...)
2591
0
{
2592
0
    va_list args;
2593
0
    va_start(args, fmt);
2594
0
    appendfv(fmt, args);
2595
0
    va_end(args);
2596
0
}
2597
2598
// Helper: Text buffer for logging/accumulating text
2599
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
2600
0
{
2601
0
    va_list args_copy;
2602
0
    va_copy(args_copy, args);
2603
2604
0
    int len = ImFormatStringV(NULL, 0, fmt, args);         // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
2605
0
    if (len <= 0)
2606
0
    {
2607
0
        va_end(args_copy);
2608
0
        return;
2609
0
    }
2610
2611
    // Add zero-terminator the first time
2612
0
    const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
2613
0
    const int needed_sz = write_off + len;
2614
0
    if (write_off + len >= Buf.Capacity)
2615
0
    {
2616
0
        int new_capacity = Buf.Capacity * 2;
2617
0
        Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
2618
0
    }
2619
2620
0
    Buf.resize(needed_sz);
2621
0
    ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
2622
0
    va_end(args_copy);
2623
0
}
2624
2625
void ImGuiTextIndex::append(const char* base, int old_size, int new_size)
2626
0
{
2627
0
    IM_ASSERT(old_size >= 0 && new_size >= old_size && new_size >= EndOffset);
2628
0
    if (old_size == new_size)
2629
0
        return;
2630
0
    if (EndOffset == 0 || base[EndOffset - 1] == '\n')
2631
0
        LineOffsets.push_back(EndOffset);
2632
0
    const char* base_end = base + new_size;
2633
0
    for (const char* p = base + old_size; (p = (const char*)memchr(p, '\n', base_end - p)) != 0; )
2634
0
        if (++p < base_end) // Don't push a trailing offset on last \n
2635
0
            LineOffsets.push_back((int)(intptr_t)(p - base));
2636
0
    EndOffset = ImMax(EndOffset, new_size);
2637
0
}
2638
2639
//-----------------------------------------------------------------------------
2640
// [SECTION] ImGuiListClipper
2641
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
2642
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
2643
//-----------------------------------------------------------------------------
2644
2645
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
2646
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
2647
static bool GetSkipItemForListClipping()
2648
0
{
2649
0
    ImGuiContext& g = *GImGui;
2650
0
    return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
2651
0
}
2652
2653
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
2654
// Legacy helper to calculate coarse clipping of large list of evenly sized items.
2655
// This legacy API is not ideal because it assumes we will return a single contiguous rectangle.
2656
// Prefer using ImGuiListClipper which can returns non-contiguous ranges.
2657
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
2658
{
2659
    ImGuiContext& g = *GImGui;
2660
    ImGuiWindow* window = g.CurrentWindow;
2661
    if (g.LogEnabled)
2662
    {
2663
        // If logging is active, do not perform any clipping
2664
        *out_items_display_start = 0;
2665
        *out_items_display_end = items_count;
2666
        return;
2667
    }
2668
    if (GetSkipItemForListClipping())
2669
    {
2670
        *out_items_display_start = *out_items_display_end = 0;
2671
        return;
2672
    }
2673
2674
    // We create the union of the ClipRect and the scoring rect which at worst should be 1 page away from ClipRect
2675
    // We don't include g.NavId's rectangle in there (unless g.NavJustMovedToId is set) because the rectangle enlargement can get costly.
2676
    ImRect rect = window->ClipRect;
2677
    if (g.NavMoveScoringItems)
2678
        rect.Add(g.NavScoringNoClipRect);
2679
    if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
2680
        rect.Add(WindowRectRelToAbs(window, window->NavRectRel[0])); // Could store and use NavJustMovedToRectRel
2681
2682
    const ImVec2 pos = window->DC.CursorPos;
2683
    int start = (int)((rect.Min.y - pos.y) / items_height);
2684
    int end = (int)((rect.Max.y - pos.y) / items_height);
2685
2686
    // When performing a navigation request, ensure we have one item extra in the direction we are moving to
2687
    // FIXME: Verify this works with tabbing
2688
    const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2689
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up)
2690
        start--;
2691
    if (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down)
2692
        end++;
2693
2694
    start = ImClamp(start, 0, items_count);
2695
    end = ImClamp(end + 1, start, items_count);
2696
    *out_items_display_start = start;
2697
    *out_items_display_end = end;
2698
}
2699
#endif
2700
2701
static void ImGuiListClipper_SortAndFuseRanges(ImVector<ImGuiListClipperRange>& ranges, int offset = 0)
2702
0
{
2703
0
    if (ranges.Size - offset <= 1)
2704
0
        return;
2705
2706
    // Helper to order ranges and fuse them together if possible (bubble sort is fine as we are only sorting 2-3 entries)
2707
0
    for (int sort_end = ranges.Size - offset - 1; sort_end > 0; --sort_end)
2708
0
        for (int i = offset; i < sort_end + offset; ++i)
2709
0
            if (ranges[i].Min > ranges[i + 1].Min)
2710
0
                ImSwap(ranges[i], ranges[i + 1]);
2711
2712
    // Now fuse ranges together as much as possible.
2713
0
    for (int i = 1 + offset; i < ranges.Size; i++)
2714
0
    {
2715
0
        IM_ASSERT(!ranges[i].PosToIndexConvert && !ranges[i - 1].PosToIndexConvert);
2716
0
        if (ranges[i - 1].Max < ranges[i].Min)
2717
0
            continue;
2718
0
        ranges[i - 1].Min = ImMin(ranges[i - 1].Min, ranges[i].Min);
2719
0
        ranges[i - 1].Max = ImMax(ranges[i - 1].Max, ranges[i].Max);
2720
0
        ranges.erase(ranges.Data + i);
2721
0
        i--;
2722
0
    }
2723
0
}
2724
2725
static void ImGuiListClipper_SeekCursorAndSetupPrevLine(float pos_y, float line_height)
2726
0
{
2727
    // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
2728
    // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
2729
    // The clipper should probably have a final step to display the last item in a regular manner, maybe with an opt-out flag for data sets which may have costly seek?
2730
0
    ImGuiContext& g = *GImGui;
2731
0
    ImGuiWindow* window = g.CurrentWindow;
2732
0
    float off_y = pos_y - window->DC.CursorPos.y;
2733
0
    window->DC.CursorPos.y = pos_y;
2734
0
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y - g.Style.ItemSpacing.y);
2735
0
    window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height;  // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
2736
0
    window->DC.PrevLineSize.y = (line_height - g.Style.ItemSpacing.y);      // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
2737
0
    if (ImGuiOldColumns* columns = window->DC.CurrentColumns)
2738
0
        columns->LineMinY = window->DC.CursorPos.y;                         // Setting this so that cell Y position are set properly
2739
0
    if (ImGuiTable* table = g.CurrentTable)
2740
0
    {
2741
0
        if (table->IsInsideRow)
2742
0
            ImGui::TableEndRow(table);
2743
0
        table->RowPosY2 = window->DC.CursorPos.y;
2744
0
        const int row_increase = (int)((off_y / line_height) + 0.5f);
2745
        //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
2746
0
        table->RowBgColorCounter += row_increase;
2747
0
    }
2748
0
}
2749
2750
static void ImGuiListClipper_SeekCursorForItem(ImGuiListClipper* clipper, int item_n)
2751
0
{
2752
    // StartPosY starts from ItemsFrozen hence the subtraction
2753
    // Perform the add and multiply with double to allow seeking through larger ranges
2754
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2755
0
    float pos_y = (float)((double)clipper->StartPosY + data->LossynessOffset + (double)(item_n - data->ItemsFrozen) * clipper->ItemsHeight);
2756
0
    ImGuiListClipper_SeekCursorAndSetupPrevLine(pos_y, clipper->ItemsHeight);
2757
0
}
2758
2759
ImGuiListClipper::ImGuiListClipper()
2760
0
{
2761
0
    memset(this, 0, sizeof(*this));
2762
0
    ItemsCount = -1;
2763
0
}
2764
2765
ImGuiListClipper::~ImGuiListClipper()
2766
0
{
2767
0
    End();
2768
0
}
2769
2770
void ImGuiListClipper::Begin(int items_count, float items_height)
2771
0
{
2772
0
    ImGuiContext& g = *GImGui;
2773
0
    ImGuiWindow* window = g.CurrentWindow;
2774
0
    IMGUI_DEBUG_LOG_CLIPPER("Clipper: Begin(%d,%.2f) in '%s'\n", items_count, items_height, window->Name);
2775
2776
0
    if (ImGuiTable* table = g.CurrentTable)
2777
0
        if (table->IsInsideRow)
2778
0
            ImGui::TableEndRow(table);
2779
2780
0
    StartPosY = window->DC.CursorPos.y;
2781
0
    ItemsHeight = items_height;
2782
0
    ItemsCount = items_count;
2783
0
    DisplayStart = -1;
2784
0
    DisplayEnd = 0;
2785
2786
    // Acquire temporary buffer
2787
0
    if (++g.ClipperTempDataStacked > g.ClipperTempData.Size)
2788
0
        g.ClipperTempData.resize(g.ClipperTempDataStacked, ImGuiListClipperData());
2789
0
    ImGuiListClipperData* data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2790
0
    data->Reset(this);
2791
0
    data->LossynessOffset = window->DC.CursorStartPosLossyness.y;
2792
0
    TempData = data;
2793
0
}
2794
2795
void ImGuiListClipper::End()
2796
0
{
2797
0
    ImGuiContext& g = *GImGui;
2798
0
    if (ImGuiListClipperData* data = (ImGuiListClipperData*)TempData)
2799
0
    {
2800
        // In theory here we should assert that we are already at the right position, but it seems saner to just seek at the end and not assert/crash the user.
2801
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: End() in '%s'\n", g.CurrentWindow->Name);
2802
0
        if (ItemsCount >= 0 && ItemsCount < INT_MAX && DisplayStart >= 0)
2803
0
            ImGuiListClipper_SeekCursorForItem(this, ItemsCount);
2804
2805
        // Restore temporary buffer and fix back pointers which may be invalidated when nesting
2806
0
        IM_ASSERT(data->ListClipper == this);
2807
0
        data->StepNo = data->Ranges.Size;
2808
0
        if (--g.ClipperTempDataStacked > 0)
2809
0
        {
2810
0
            data = &g.ClipperTempData[g.ClipperTempDataStacked - 1];
2811
0
            data->ListClipper->TempData = data;
2812
0
        }
2813
0
        TempData = NULL;
2814
0
    }
2815
0
    ItemsCount = -1;
2816
0
}
2817
2818
void ImGuiListClipper::ForceDisplayRangeByIndices(int item_min, int item_max)
2819
0
{
2820
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)TempData;
2821
0
    IM_ASSERT(DisplayStart < 0); // Only allowed after Begin() and if there has not been a specified range yet.
2822
0
    IM_ASSERT(item_min <= item_max);
2823
0
    if (item_min < item_max)
2824
0
        data->Ranges.push_back(ImGuiListClipperRange::FromIndices(item_min, item_max));
2825
0
}
2826
2827
static bool ImGuiListClipper_StepInternal(ImGuiListClipper* clipper)
2828
0
{
2829
0
    ImGuiContext& g = *GImGui;
2830
0
    ImGuiWindow* window = g.CurrentWindow;
2831
0
    ImGuiListClipperData* data = (ImGuiListClipperData*)clipper->TempData;
2832
0
    IM_ASSERT(data != NULL && "Called ImGuiListClipper::Step() too many times, or before ImGuiListClipper::Begin() ?");
2833
2834
0
    ImGuiTable* table = g.CurrentTable;
2835
0
    if (table && table->IsInsideRow)
2836
0
        ImGui::TableEndRow(table);
2837
2838
    // No items
2839
0
    if (clipper->ItemsCount == 0 || GetSkipItemForListClipping())
2840
0
        return false;
2841
2842
    // While we are in frozen row state, keep displaying items one by one, unclipped
2843
    // FIXME: Could be stored as a table-agnostic state.
2844
0
    if (data->StepNo == 0 && table != NULL && !table->IsUnfrozenRows)
2845
0
    {
2846
0
        clipper->DisplayStart = data->ItemsFrozen;
2847
0
        clipper->DisplayEnd = ImMin(data->ItemsFrozen + 1, clipper->ItemsCount);
2848
0
        if (clipper->DisplayStart < clipper->DisplayEnd)
2849
0
            data->ItemsFrozen++;
2850
0
        return true;
2851
0
    }
2852
2853
    // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
2854
0
    bool calc_clipping = false;
2855
0
    if (data->StepNo == 0)
2856
0
    {
2857
0
        clipper->StartPosY = window->DC.CursorPos.y;
2858
0
        if (clipper->ItemsHeight <= 0.0f)
2859
0
        {
2860
            // Submit the first item (or range) so we can measure its height (generally the first range is 0..1)
2861
0
            data->Ranges.push_front(ImGuiListClipperRange::FromIndices(data->ItemsFrozen, data->ItemsFrozen + 1));
2862
0
            clipper->DisplayStart = ImMax(data->Ranges[0].Min, data->ItemsFrozen);
2863
0
            clipper->DisplayEnd = ImMin(data->Ranges[0].Max, clipper->ItemsCount);
2864
0
            data->StepNo = 1;
2865
0
            return true;
2866
0
        }
2867
0
        calc_clipping = true;   // If on the first step with known item height, calculate clipping.
2868
0
    }
2869
2870
    // Step 1: Let the clipper infer height from first range
2871
0
    if (clipper->ItemsHeight <= 0.0f)
2872
0
    {
2873
0
        IM_ASSERT(data->StepNo == 1);
2874
0
        if (table)
2875
0
            IM_ASSERT(table->RowPosY1 == clipper->StartPosY && table->RowPosY2 == window->DC.CursorPos.y);
2876
2877
0
        clipper->ItemsHeight = (window->DC.CursorPos.y - clipper->StartPosY) / (float)(clipper->DisplayEnd - clipper->DisplayStart);
2878
0
        bool affected_by_floating_point_precision = ImIsFloatAboveGuaranteedIntegerPrecision(clipper->StartPosY) || ImIsFloatAboveGuaranteedIntegerPrecision(window->DC.CursorPos.y);
2879
0
        if (affected_by_floating_point_precision)
2880
0
            clipper->ItemsHeight = window->DC.PrevLineSize.y + g.Style.ItemSpacing.y; // FIXME: Technically wouldn't allow multi-line entries.
2881
2882
0
        IM_ASSERT(clipper->ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
2883
0
        calc_clipping = true;   // If item height had to be calculated, calculate clipping afterwards.
2884
0
    }
2885
2886
    // Step 0 or 1: Calculate the actual ranges of visible elements.
2887
0
    const int already_submitted = clipper->DisplayEnd;
2888
0
    if (calc_clipping)
2889
0
    {
2890
0
        if (g.LogEnabled)
2891
0
        {
2892
            // If logging is active, do not perform any clipping
2893
0
            data->Ranges.push_back(ImGuiListClipperRange::FromIndices(0, clipper->ItemsCount));
2894
0
        }
2895
0
        else
2896
0
        {
2897
            // Add range selected to be included for navigation
2898
0
            const bool is_nav_request = (g.NavMoveScoringItems && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
2899
0
            if (is_nav_request)
2900
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(g.NavScoringNoClipRect.Min.y, g.NavScoringNoClipRect.Max.y, 0, 0));
2901
0
            if (is_nav_request && (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && g.NavTabbingDir == -1)
2902
0
                data->Ranges.push_back(ImGuiListClipperRange::FromIndices(clipper->ItemsCount - 1, clipper->ItemsCount));
2903
2904
            // Add focused/active item
2905
0
            ImRect nav_rect_abs = ImGui::WindowRectRelToAbs(window, window->NavRectRel[0]);
2906
0
            if (g.NavId != 0 && window->NavLastIds[0] == g.NavId)
2907
0
                data->Ranges.push_back(ImGuiListClipperRange::FromPositions(nav_rect_abs.Min.y, nav_rect_abs.Max.y, 0, 0));
2908
2909
            // Add visible range
2910
0
            const int off_min = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Up) ? -1 : 0;
2911
0
            const int off_max = (is_nav_request && g.NavMoveClipDir == ImGuiDir_Down) ? 1 : 0;
2912
0
            data->Ranges.push_back(ImGuiListClipperRange::FromPositions(window->ClipRect.Min.y, window->ClipRect.Max.y, off_min, off_max));
2913
0
        }
2914
2915
        // Convert position ranges to item index ranges
2916
        // - Very important: when a starting position is after our maximum item, we set Min to (ItemsCount - 1). This allows us to handle most forms of wrapping.
2917
        // - Due to how Selectable extra padding they tend to be "unaligned" with exact unit in the item list,
2918
        //   which with the flooring/ceiling tend to lead to 2 items instead of one being submitted.
2919
0
        for (int i = 0; i < data->Ranges.Size; i++)
2920
0
            if (data->Ranges[i].PosToIndexConvert)
2921
0
            {
2922
0
                int m1 = (int)(((double)data->Ranges[i].Min - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight);
2923
0
                int m2 = (int)((((double)data->Ranges[i].Max - window->DC.CursorPos.y - data->LossynessOffset) / clipper->ItemsHeight) + 0.999999f);
2924
0
                data->Ranges[i].Min = ImClamp(already_submitted + m1 + data->Ranges[i].PosToIndexOffsetMin, already_submitted, clipper->ItemsCount - 1);
2925
0
                data->Ranges[i].Max = ImClamp(already_submitted + m2 + data->Ranges[i].PosToIndexOffsetMax, data->Ranges[i].Min + 1, clipper->ItemsCount);
2926
0
                data->Ranges[i].PosToIndexConvert = false;
2927
0
            }
2928
0
        ImGuiListClipper_SortAndFuseRanges(data->Ranges, data->StepNo);
2929
0
    }
2930
2931
    // Step 0+ (if item height is given in advance) or 1+: Display the next range in line.
2932
0
    if (data->StepNo < data->Ranges.Size)
2933
0
    {
2934
0
        clipper->DisplayStart = ImMax(data->Ranges[data->StepNo].Min, already_submitted);
2935
0
        clipper->DisplayEnd = ImMin(data->Ranges[data->StepNo].Max, clipper->ItemsCount);
2936
0
        if (clipper->DisplayStart > already_submitted) //-V1051
2937
0
            ImGuiListClipper_SeekCursorForItem(clipper, clipper->DisplayStart);
2938
0
        data->StepNo++;
2939
0
        return true;
2940
0
    }
2941
2942
    // After the last step: Let the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd),
2943
    // Advance the cursor to the end of the list and then returns 'false' to end the loop.
2944
0
    if (clipper->ItemsCount < INT_MAX)
2945
0
        ImGuiListClipper_SeekCursorForItem(clipper, clipper->ItemsCount);
2946
2947
0
    return false;
2948
0
}
2949
2950
bool ImGuiListClipper::Step()
2951
0
{
2952
0
    ImGuiContext& g = *GImGui;
2953
0
    bool need_items_height = (ItemsHeight <= 0.0f);
2954
0
    bool ret = ImGuiListClipper_StepInternal(this);
2955
0
    if (ret && (DisplayStart == DisplayEnd))
2956
0
        ret = false;
2957
0
    if (g.CurrentTable && g.CurrentTable->IsUnfrozenRows == false)
2958
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): inside frozen table row.\n");
2959
0
    if (need_items_height && ItemsHeight > 0.0f)
2960
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): computed ItemsHeight: %.2f.\n", ItemsHeight);
2961
0
    if (ret)
2962
0
    {
2963
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): display %d to %d.\n", DisplayStart, DisplayEnd);
2964
0
    }
2965
0
    else
2966
0
    {
2967
0
        IMGUI_DEBUG_LOG_CLIPPER("Clipper: Step(): End.\n");
2968
0
        End();
2969
0
    }
2970
0
    return ret;
2971
0
}
2972
2973
//-----------------------------------------------------------------------------
2974
// [SECTION] STYLING
2975
//-----------------------------------------------------------------------------
2976
2977
ImGuiStyle& ImGui::GetStyle()
2978
81.4k
{
2979
81.4k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
2980
81.4k
    return GImGui->Style;
2981
81.4k
}
2982
2983
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
2984
428k
{
2985
428k
    ImGuiStyle& style = GImGui->Style;
2986
428k
    ImVec4 c = style.Colors[idx];
2987
428k
    c.w *= style.Alpha * alpha_mul;
2988
428k
    return ColorConvertFloat4ToU32(c);
2989
428k
}
2990
2991
ImU32 ImGui::GetColorU32(const ImVec4& col)
2992
0
{
2993
0
    ImGuiStyle& style = GImGui->Style;
2994
0
    ImVec4 c = col;
2995
0
    c.w *= style.Alpha;
2996
0
    return ColorConvertFloat4ToU32(c);
2997
0
}
2998
2999
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
3000
0
{
3001
0
    ImGuiStyle& style = GImGui->Style;
3002
0
    return style.Colors[idx];
3003
0
}
3004
3005
ImU32 ImGui::GetColorU32(ImU32 col)
3006
0
{
3007
0
    ImGuiStyle& style = GImGui->Style;
3008
0
    if (style.Alpha >= 1.0f)
3009
0
        return col;
3010
0
    ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
3011
0
    a = (ImU32)(a * style.Alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
3012
0
    return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
3013
0
}
3014
3015
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
3016
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
3017
0
{
3018
0
    ImGuiContext& g = *GImGui;
3019
0
    ImGuiColorMod backup;
3020
0
    backup.Col = idx;
3021
0
    backup.BackupValue = g.Style.Colors[idx];
3022
0
    g.ColorStack.push_back(backup);
3023
0
    g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
3024
0
}
3025
3026
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
3027
34.4k
{
3028
34.4k
    ImGuiContext& g = *GImGui;
3029
34.4k
    ImGuiColorMod backup;
3030
34.4k
    backup.Col = idx;
3031
34.4k
    backup.BackupValue = g.Style.Colors[idx];
3032
34.4k
    g.ColorStack.push_back(backup);
3033
34.4k
    g.Style.Colors[idx] = col;
3034
34.4k
}
3035
3036
void ImGui::PopStyleColor(int count)
3037
34.4k
{
3038
34.4k
    ImGuiContext& g = *GImGui;
3039
34.4k
    if (g.ColorStack.Size < count)
3040
0
    {
3041
0
        IM_ASSERT_USER_ERROR(g.ColorStack.Size > count, "Calling PopStyleColor() too many times: stack underflow.");
3042
0
        count = g.ColorStack.Size;
3043
0
    }
3044
68.8k
    while (count > 0)
3045
34.4k
    {
3046
34.4k
        ImGuiColorMod& backup = g.ColorStack.back();
3047
34.4k
        g.Style.Colors[backup.Col] = backup.BackupValue;
3048
34.4k
        g.ColorStack.pop_back();
3049
34.4k
        count--;
3050
34.4k
    }
3051
34.4k
}
3052
3053
struct ImGuiStyleVarInfo
3054
{
3055
    ImGuiDataType   Type;
3056
    ImU32           Count;
3057
    ImU32           Offset;
3058
68.8k
    void*           GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
3059
};
3060
3061
static const ImGuiCol GWindowDockStyleColors[ImGuiWindowDockStyleCol_COUNT] =
3062
{
3063
    ImGuiCol_Text, ImGuiCol_Tab, ImGuiCol_TabHovered, ImGuiCol_TabActive, ImGuiCol_TabUnfocused, ImGuiCol_TabUnfocusedActive
3064
};
3065
3066
static const ImGuiStyleVarInfo GStyleVarInfo[] =
3067
{
3068
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) },               // ImGuiStyleVar_Alpha
3069
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, DisabledAlpha) },       // ImGuiStyleVar_DisabledAlpha
3070
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) },       // ImGuiStyleVar_WindowPadding
3071
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) },      // ImGuiStyleVar_WindowRounding
3072
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) },    // ImGuiStyleVar_WindowBorderSize
3073
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) },       // ImGuiStyleVar_WindowMinSize
3074
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) },    // ImGuiStyleVar_WindowTitleAlign
3075
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) },       // ImGuiStyleVar_ChildRounding
3076
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) },     // ImGuiStyleVar_ChildBorderSize
3077
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) },       // ImGuiStyleVar_PopupRounding
3078
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) },     // ImGuiStyleVar_PopupBorderSize
3079
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) },        // ImGuiStyleVar_FramePadding
3080
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) },       // ImGuiStyleVar_FrameRounding
3081
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) },     // ImGuiStyleVar_FrameBorderSize
3082
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) },         // ImGuiStyleVar_ItemSpacing
3083
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) },    // ImGuiStyleVar_ItemInnerSpacing
3084
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) },       // ImGuiStyleVar_IndentSpacing
3085
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) },         // ImGuiStyleVar_CellPadding
3086
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) },       // ImGuiStyleVar_ScrollbarSize
3087
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) },   // ImGuiStyleVar_ScrollbarRounding
3088
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) },         // ImGuiStyleVar_GrabMinSize
3089
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) },        // ImGuiStyleVar_GrabRounding
3090
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) },         // ImGuiStyleVar_TabRounding
3091
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) },     // ImGuiStyleVar_ButtonTextAlign
3092
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
3093
    { ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextBorderSize) },// ImGuiStyleVar_SeparatorTextBorderSize
3094
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextAlign) },     // ImGuiStyleVar_SeparatorTextAlign
3095
    { ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SeparatorTextPadding) },   // ImGuiStyleVar_SeparatorTextPadding
3096
};
3097
3098
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
3099
68.8k
{
3100
68.8k
    IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
3101
68.8k
    IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
3102
68.8k
    return &GStyleVarInfo[idx];
3103
68.8k
}
3104
3105
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
3106
0
{
3107
0
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3108
0
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
3109
0
    {
3110
0
        ImGuiContext& g = *GImGui;
3111
0
        float* pvar = (float*)var_info->GetVarPtr(&g.Style);
3112
0
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3113
0
        *pvar = val;
3114
0
        return;
3115
0
    }
3116
0
    IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
3117
0
}
3118
3119
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
3120
34.4k
{
3121
34.4k
    const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
3122
34.4k
    if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
3123
34.4k
    {
3124
34.4k
        ImGuiContext& g = *GImGui;
3125
34.4k
        ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
3126
34.4k
        g.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
3127
34.4k
        *pvar = val;
3128
34.4k
        return;
3129
34.4k
    }
3130
0
    IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
3131
0
}
3132
3133
void ImGui::PopStyleVar(int count)
3134
34.4k
{
3135
34.4k
    ImGuiContext& g = *GImGui;
3136
34.4k
    if (g.StyleVarStack.Size < count)
3137
0
    {
3138
0
        IM_ASSERT_USER_ERROR(g.StyleVarStack.Size > count, "Calling PopStyleVar() too many times: stack underflow.");
3139
0
        count = g.StyleVarStack.Size;
3140
0
    }
3141
68.8k
    while (count > 0)
3142
34.4k
    {
3143
        // We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
3144
34.4k
        ImGuiStyleMod& backup = g.StyleVarStack.back();
3145
34.4k
        const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
3146
34.4k
        void* data = info->GetVarPtr(&g.Style);
3147
34.4k
        if (info->Type == ImGuiDataType_Float && info->Count == 1)      { ((float*)data)[0] = backup.BackupFloat[0]; }
3148
34.4k
        else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
3149
34.4k
        g.StyleVarStack.pop_back();
3150
34.4k
        count--;
3151
34.4k
    }
3152
34.4k
}
3153
3154
const char* ImGui::GetStyleColorName(ImGuiCol idx)
3155
0
{
3156
    // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
3157
0
    switch (idx)
3158
0
    {
3159
0
    case ImGuiCol_Text: return "Text";
3160
0
    case ImGuiCol_TextDisabled: return "TextDisabled";
3161
0
    case ImGuiCol_WindowBg: return "WindowBg";
3162
0
    case ImGuiCol_ChildBg: return "ChildBg";
3163
0
    case ImGuiCol_PopupBg: return "PopupBg";
3164
0
    case ImGuiCol_Border: return "Border";
3165
0
    case ImGuiCol_BorderShadow: return "BorderShadow";
3166
0
    case ImGuiCol_FrameBg: return "FrameBg";
3167
0
    case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
3168
0
    case ImGuiCol_FrameBgActive: return "FrameBgActive";
3169
0
    case ImGuiCol_TitleBg: return "TitleBg";
3170
0
    case ImGuiCol_TitleBgActive: return "TitleBgActive";
3171
0
    case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
3172
0
    case ImGuiCol_MenuBarBg: return "MenuBarBg";
3173
0
    case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
3174
0
    case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
3175
0
    case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
3176
0
    case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
3177
0
    case ImGuiCol_CheckMark: return "CheckMark";
3178
0
    case ImGuiCol_SliderGrab: return "SliderGrab";
3179
0
    case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
3180
0
    case ImGuiCol_Button: return "Button";
3181
0
    case ImGuiCol_ButtonHovered: return "ButtonHovered";
3182
0
    case ImGuiCol_ButtonActive: return "ButtonActive";
3183
0
    case ImGuiCol_Header: return "Header";
3184
0
    case ImGuiCol_HeaderHovered: return "HeaderHovered";
3185
0
    case ImGuiCol_HeaderActive: return "HeaderActive";
3186
0
    case ImGuiCol_Separator: return "Separator";
3187
0
    case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
3188
0
    case ImGuiCol_SeparatorActive: return "SeparatorActive";
3189
0
    case ImGuiCol_ResizeGrip: return "ResizeGrip";
3190
0
    case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
3191
0
    case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
3192
0
    case ImGuiCol_Tab: return "Tab";
3193
0
    case ImGuiCol_TabHovered: return "TabHovered";
3194
0
    case ImGuiCol_TabActive: return "TabActive";
3195
0
    case ImGuiCol_TabUnfocused: return "TabUnfocused";
3196
0
    case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
3197
0
    case ImGuiCol_DockingPreview: return "DockingPreview";
3198
0
    case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
3199
0
    case ImGuiCol_PlotLines: return "PlotLines";
3200
0
    case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
3201
0
    case ImGuiCol_PlotHistogram: return "PlotHistogram";
3202
0
    case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
3203
0
    case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
3204
0
    case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
3205
0
    case ImGuiCol_TableBorderLight: return "TableBorderLight";
3206
0
    case ImGuiCol_TableRowBg: return "TableRowBg";
3207
0
    case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
3208
0
    case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
3209
0
    case ImGuiCol_DragDropTarget: return "DragDropTarget";
3210
0
    case ImGuiCol_NavHighlight: return "NavHighlight";
3211
0
    case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
3212
0
    case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
3213
0
    case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
3214
0
    }
3215
0
    IM_ASSERT(0);
3216
0
    return "Unknown";
3217
0
}
3218
3219
3220
//-----------------------------------------------------------------------------
3221
// [SECTION] RENDER HELPERS
3222
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
3223
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
3224
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
3225
//-----------------------------------------------------------------------------
3226
3227
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
3228
137k
{
3229
137k
    const char* text_display_end = text;
3230
137k
    if (!text_end)
3231
137k
        text_end = (const char*)-1;
3232
3233
1.24M
    while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
3234
1.10M
        text_display_end++;
3235
137k
    return text_display_end;
3236
137k
}
3237
3238
// Internal ImGui functions to render text
3239
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
3240
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
3241
0
{
3242
0
    ImGuiContext& g = *GImGui;
3243
0
    ImGuiWindow* window = g.CurrentWindow;
3244
3245
    // Hide anything after a '##' string
3246
0
    const char* text_display_end;
3247
0
    if (hide_text_after_hash)
3248
0
    {
3249
0
        text_display_end = FindRenderedTextEnd(text, text_end);
3250
0
    }
3251
0
    else
3252
0
    {
3253
0
        if (!text_end)
3254
0
            text_end = text + strlen(text); // FIXME-OPT
3255
0
        text_display_end = text_end;
3256
0
    }
3257
3258
0
    if (text != text_display_end)
3259
0
    {
3260
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
3261
0
        if (g.LogEnabled)
3262
0
            LogRenderedText(&pos, text, text_display_end);
3263
0
    }
3264
0
}
3265
3266
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
3267
0
{
3268
0
    ImGuiContext& g = *GImGui;
3269
0
    ImGuiWindow* window = g.CurrentWindow;
3270
3271
0
    if (!text_end)
3272
0
        text_end = text + strlen(text); // FIXME-OPT
3273
3274
0
    if (text != text_end)
3275
0
    {
3276
0
        window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
3277
0
        if (g.LogEnabled)
3278
0
            LogRenderedText(&pos, text, text_end);
3279
0
    }
3280
0
}
3281
3282
// Default clip_rect uses (pos_min,pos_max)
3283
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
3284
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3285
68.8k
{
3286
    // Perform CPU side clipping for single clipped element to avoid using scissor state
3287
68.8k
    ImVec2 pos = pos_min;
3288
68.8k
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
3289
3290
68.8k
    const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
3291
68.8k
    const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
3292
68.8k
    bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
3293
68.8k
    if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
3294
68.8k
        need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
3295
3296
    // Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
3297
68.8k
    if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
3298
68.8k
    if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
3299
3300
    // Render
3301
68.8k
    if (need_clipping)
3302
34.4k
    {
3303
34.4k
        ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
3304
34.4k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
3305
34.4k
    }
3306
34.4k
    else
3307
34.4k
    {
3308
34.4k
        draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
3309
34.4k
    }
3310
68.8k
}
3311
3312
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
3313
68.8k
{
3314
    // Hide anything after a '##' string
3315
68.8k
    const char* text_display_end = FindRenderedTextEnd(text, text_end);
3316
68.8k
    const int text_len = (int)(text_display_end - text);
3317
68.8k
    if (text_len == 0)
3318
0
        return;
3319
3320
68.8k
    ImGuiContext& g = *GImGui;
3321
68.8k
    ImGuiWindow* window = g.CurrentWindow;
3322
68.8k
    RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
3323
68.8k
    if (g.LogEnabled)
3324
0
        LogRenderedText(&pos_min, text, text_display_end);
3325
68.8k
}
3326
3327
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
3328
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
3329
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
3330
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
3331
0
{
3332
0
    ImGuiContext& g = *GImGui;
3333
0
    if (text_end_full == NULL)
3334
0
        text_end_full = FindRenderedTextEnd(text);
3335
0
    const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
3336
3337
    //draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
3338
    //draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
3339
    //draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
3340
    // FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
3341
0
    if (text_size.x > pos_max.x - pos_min.x)
3342
0
    {
3343
        // Hello wo...
3344
        // |       |   |
3345
        // min   max   ellipsis_max
3346
        //          <-> this is generally some padding value
3347
3348
0
        const ImFont* font = draw_list->_Data->Font;
3349
0
        const float font_size = draw_list->_Data->FontSize;
3350
0
        const float font_scale = font_size / font->FontSize;
3351
0
        const char* text_end_ellipsis = NULL;
3352
0
        const float ellipsis_width = font->EllipsisWidth * font_scale;
3353
3354
        // We can now claim the space between pos_max.x and ellipsis_max.x
3355
0
        const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_width) - pos_min.x, 1.0f);
3356
0
        float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
3357
0
        if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
3358
0
        {
3359
            // Always display at least 1 character if there's no room for character + ellipsis
3360
0
            text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
3361
0
            text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
3362
0
        }
3363
0
        while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
3364
0
        {
3365
            // Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
3366
0
            text_end_ellipsis--;
3367
0
            text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
3368
0
        }
3369
3370
        // Render text, render ellipsis
3371
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
3372
0
        ImVec2 ellipsis_pos = ImFloor(ImVec2(pos_min.x + text_size_clipped_x, pos_min.y));
3373
0
        if (ellipsis_pos.x + ellipsis_width <= ellipsis_max_x)
3374
0
            for (int i = 0; i < font->EllipsisCharCount; i++, ellipsis_pos.x += font->EllipsisCharStep * font_scale)
3375
0
                font->RenderChar(draw_list, font_size, ellipsis_pos, GetColorU32(ImGuiCol_Text), font->EllipsisChar);
3376
0
    }
3377
0
    else
3378
0
    {
3379
0
        RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
3380
0
    }
3381
3382
0
    if (g.LogEnabled)
3383
0
        LogRenderedText(&pos_min, text, text_end_full);
3384
0
}
3385
3386
// Render a rectangle shaped with optional rounding and borders
3387
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
3388
31.4k
{
3389
31.4k
    ImGuiContext& g = *GImGui;
3390
31.4k
    ImGuiWindow* window = g.CurrentWindow;
3391
31.4k
    window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
3392
31.4k
    const float border_size = g.Style.FrameBorderSize;
3393
31.4k
    if (border && border_size > 0.0f)
3394
31.4k
    {
3395
31.4k
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3396
31.4k
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3397
31.4k
    }
3398
31.4k
}
3399
3400
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
3401
0
{
3402
0
    ImGuiContext& g = *GImGui;
3403
0
    ImGuiWindow* window = g.CurrentWindow;
3404
0
    const float border_size = g.Style.FrameBorderSize;
3405
0
    if (border_size > 0.0f)
3406
0
    {
3407
0
        window->DrawList->AddRect(p_min + ImVec2(1, 1), p_max + ImVec2(1, 1), GetColorU32(ImGuiCol_BorderShadow), rounding, 0, border_size);
3408
0
        window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
3409
0
    }
3410
0
}
3411
3412
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
3413
2.71k
{
3414
2.71k
    ImGuiContext& g = *GImGui;
3415
2.71k
    if (id != g.NavId)
3416
1.51k
        return;
3417
1.19k
    if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
3418
440
        return;
3419
752
    ImGuiWindow* window = g.CurrentWindow;
3420
752
    if (window->DC.NavHideHighlightOneFrame)
3421
0
        return;
3422
3423
752
    float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
3424
752
    ImRect display_rect = bb;
3425
752
    display_rect.ClipWith(window->ClipRect);
3426
752
    if (flags & ImGuiNavHighlightFlags_TypeDefault)
3427
93
    {
3428
93
        const float THICKNESS = 2.0f;
3429
93
        const float DISTANCE = 3.0f + THICKNESS * 0.5f;
3430
93
        display_rect.Expand(ImVec2(DISTANCE, DISTANCE));
3431
93
        bool fully_visible = window->ClipRect.Contains(display_rect);
3432
93
        if (!fully_visible)
3433
68
            window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
3434
93
        window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), display_rect.Max - ImVec2(THICKNESS * 0.5f, THICKNESS * 0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, 0, THICKNESS);
3435
93
        if (!fully_visible)
3436
68
            window->DrawList->PopClipRect();
3437
93
    }
3438
752
    if (flags & ImGuiNavHighlightFlags_TypeThin)
3439
659
    {
3440
659
        window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, 0, 1.0f);
3441
659
    }
3442
752
}
3443
3444
void ImGui::RenderMouseCursor(ImVec2 base_pos, float base_scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
3445
0
{
3446
0
    ImGuiContext& g = *GImGui;
3447
0
    IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
3448
0
    ImFontAtlas* font_atlas = g.DrawListSharedData.Font->ContainerAtlas;
3449
0
    for (int n = 0; n < g.Viewports.Size; n++)
3450
0
    {
3451
        // We scale cursor with current viewport/monitor, however Windows 10 for its own hardware cursor seems to be using a different scale factor.
3452
0
        ImVec2 offset, size, uv[4];
3453
0
        if (!font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
3454
0
            continue;
3455
0
        ImGuiViewportP* viewport = g.Viewports[n];
3456
0
        const ImVec2 pos = base_pos - offset;
3457
0
        const float scale = base_scale * viewport->DpiScale;
3458
0
        if (!viewport->GetMainRect().Overlaps(ImRect(pos, pos + ImVec2(size.x + 2, size.y + 2) * scale)))
3459
0
            continue;
3460
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
3461
0
        ImTextureID tex_id = font_atlas->TexID;
3462
0
        draw_list->PushTextureID(tex_id);
3463
0
        draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
3464
0
        draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
3465
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[2], uv[3], col_border);
3466
0
        draw_list->AddImage(tex_id, pos,                        pos + size * scale,                  uv[0], uv[1], col_fill);
3467
0
        draw_list->PopTextureID();
3468
0
    }
3469
0
}
3470
3471
//-----------------------------------------------------------------------------
3472
// [SECTION] INITIALIZATION, SHUTDOWN
3473
//-----------------------------------------------------------------------------
3474
3475
// Internal state access - if you want to share Dear ImGui state between modules (e.g. DLL) or allocate it yourself
3476
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
3477
ImGuiContext* ImGui::GetCurrentContext()
3478
1
{
3479
1
    return GImGui;
3480
1
}
3481
3482
void ImGui::SetCurrentContext(ImGuiContext* ctx)
3483
1
{
3484
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
3485
    IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
3486
#else
3487
1
    GImGui = ctx;
3488
1
#endif
3489
1
}
3490
3491
void ImGui::SetAllocatorFunctions(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
3492
0
{
3493
0
    GImAllocatorAllocFunc = alloc_func;
3494
0
    GImAllocatorFreeFunc = free_func;
3495
0
    GImAllocatorUserData = user_data;
3496
0
}
3497
3498
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
3499
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
3500
0
{
3501
0
    *p_alloc_func = GImAllocatorAllocFunc;
3502
0
    *p_free_func = GImAllocatorFreeFunc;
3503
0
    *p_user_data = GImAllocatorUserData;
3504
0
}
3505
3506
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
3507
1
{
3508
1
    ImGuiContext* prev_ctx = GetCurrentContext();
3509
1
    ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
3510
1
    SetCurrentContext(ctx);
3511
1
    Initialize();
3512
1
    if (prev_ctx != NULL)
3513
0
        SetCurrentContext(prev_ctx); // Restore previous context if any, else keep new one.
3514
1
    return ctx;
3515
1
}
3516
3517
void ImGui::DestroyContext(ImGuiContext* ctx)
3518
0
{
3519
0
    ImGuiContext* prev_ctx = GetCurrentContext();
3520
0
    if (ctx == NULL) //-V1051
3521
0
        ctx = prev_ctx;
3522
0
    SetCurrentContext(ctx);
3523
0
    Shutdown();
3524
0
    SetCurrentContext((prev_ctx != ctx) ? prev_ctx : NULL);
3525
0
    IM_DELETE(ctx);
3526
0
}
3527
3528
// IMPORTANT: ###xxx suffixes must be same in ALL languages
3529
static const ImGuiLocEntry GLocalizationEntriesEnUS[] =
3530
{
3531
    { ImGuiLocKey_TableSizeOne,         "Size column to fit###SizeOne"          },
3532
    { ImGuiLocKey_TableSizeAllFit,      "Size all columns to fit###SizeAll"     },
3533
    { ImGuiLocKey_TableSizeAllDefault,  "Size all columns to default###SizeAll" },
3534
    { ImGuiLocKey_TableResetOrder,      "Reset order###ResetOrder"              },
3535
    { ImGuiLocKey_WindowingMainMenuBar, "(Main menu bar)"                       },
3536
    { ImGuiLocKey_WindowingPopup,       "(Popup)"                               },
3537
    { ImGuiLocKey_WindowingUntitled,    "(Untitled)"                            },
3538
    { ImGuiLocKey_DockingHideTabBar,    "Hide tab bar###HideTabBar"             },
3539
};
3540
3541
void ImGui::Initialize()
3542
1
{
3543
1
    ImGuiContext& g = *GImGui;
3544
1
    IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
3545
3546
    // Add .ini handle for ImGuiWindow and ImGuiTable types
3547
1
    {
3548
1
        ImGuiSettingsHandler ini_handler;
3549
1
        ini_handler.TypeName = "Window";
3550
1
        ini_handler.TypeHash = ImHashStr("Window");
3551
1
        ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
3552
1
        ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
3553
1
        ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
3554
1
        ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
3555
1
        ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
3556
1
        AddSettingsHandler(&ini_handler);
3557
1
    }
3558
1
    TableSettingsAddSettingsHandler();
3559
3560
    // Setup default localization table
3561
1
    LocalizeRegisterEntries(GLocalizationEntriesEnUS, IM_ARRAYSIZE(GLocalizationEntriesEnUS));
3562
3563
    // Create default viewport
3564
1
    ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
3565
1
    viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
3566
1
    viewport->Idx = 0;
3567
1
    viewport->PlatformWindowCreated = true;
3568
1
    viewport->Flags = ImGuiViewportFlags_OwnedByApp;
3569
1
    g.Viewports.push_back(viewport);
3570
1
    g.TempBuffer.resize(1024 * 3 + 1, 0);
3571
1
    g.PlatformIO.Viewports.push_back(g.Viewports[0]);
3572
3573
1
#ifdef IMGUI_HAS_DOCK
3574
    // Initialize Docking
3575
1
    DockContextInitialize(&g);
3576
1
#endif
3577
3578
1
    g.Initialized = true;
3579
1
}
3580
3581
// This function is merely here to free heap allocations.
3582
void ImGui::Shutdown()
3583
0
{
3584
    // The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
3585
0
    ImGuiContext& g = *GImGui;
3586
0
    if (g.IO.Fonts && g.FontAtlasOwnedByContext)
3587
0
    {
3588
0
        g.IO.Fonts->Locked = false;
3589
0
        IM_DELETE(g.IO.Fonts);
3590
0
    }
3591
0
    g.IO.Fonts = NULL;
3592
0
    g.DrawListSharedData.TempBuffer.clear();
3593
3594
    // Cleanup of other data are conditional on actually having initialized Dear ImGui.
3595
0
    if (!g.Initialized)
3596
0
        return;
3597
3598
    // Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
3599
0
    if (g.SettingsLoaded && g.IO.IniFilename != NULL)
3600
0
        SaveIniSettingsToDisk(g.IO.IniFilename);
3601
3602
    // Destroy platform windows
3603
0
    DestroyPlatformWindows();
3604
3605
    // Shutdown extensions
3606
0
    DockContextShutdown(&g);
3607
3608
0
    CallContextHooks(&g, ImGuiContextHookType_Shutdown);
3609
3610
    // Clear everything else
3611
0
    g.Windows.clear_delete();
3612
0
    g.WindowsFocusOrder.clear();
3613
0
    g.WindowsTempSortBuffer.clear();
3614
0
    g.CurrentWindow = NULL;
3615
0
    g.CurrentWindowStack.clear();
3616
0
    g.WindowsById.Clear();
3617
0
    g.NavWindow = NULL;
3618
0
    g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
3619
0
    g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
3620
0
    g.MovingWindow = NULL;
3621
3622
0
    g.KeysRoutingTable.Clear();
3623
3624
0
    g.ColorStack.clear();
3625
0
    g.StyleVarStack.clear();
3626
0
    g.FontStack.clear();
3627
0
    g.OpenPopupStack.clear();
3628
0
    g.BeginPopupStack.clear();
3629
3630
0
    g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
3631
0
    g.Viewports.clear_delete();
3632
3633
0
    g.TabBars.Clear();
3634
0
    g.CurrentTabBarStack.clear();
3635
0
    g.ShrinkWidthBuffer.clear();
3636
3637
0
    g.ClipperTempData.clear_destruct();
3638
3639
0
    g.Tables.Clear();
3640
0
    g.TablesTempData.clear_destruct();
3641
0
    g.DrawChannelsTempMergeBuffer.clear();
3642
3643
0
    g.ClipboardHandlerData.clear();
3644
0
    g.MenusIdSubmittedThisFrame.clear();
3645
0
    g.InputTextState.ClearFreeMemory();
3646
3647
0
    g.SettingsWindows.clear();
3648
0
    g.SettingsHandlers.clear();
3649
3650
0
    if (g.LogFile)
3651
0
    {
3652
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
3653
0
        if (g.LogFile != stdout)
3654
0
#endif
3655
0
            ImFileClose(g.LogFile);
3656
0
        g.LogFile = NULL;
3657
0
    }
3658
0
    g.LogBuffer.clear();
3659
0
    g.DebugLogBuf.clear();
3660
0
    g.DebugLogIndex.clear();
3661
3662
0
    g.Initialized = false;
3663
0
}
3664
3665
// No specific ordering/dependency support, will see as needed
3666
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
3667
0
{
3668
0
    ImGuiContext& g = *ctx;
3669
0
    IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
3670
0
    g.Hooks.push_back(*hook);
3671
0
    g.Hooks.back().HookId = ++g.HookIdNext;
3672
0
    return g.HookIdNext;
3673
0
}
3674
3675
// Deferred removal, avoiding issue with changing vector while iterating it
3676
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
3677
0
{
3678
0
    ImGuiContext& g = *ctx;
3679
0
    IM_ASSERT(hook_id != 0);
3680
0
    for (int n = 0; n < g.Hooks.Size; n++)
3681
0
        if (g.Hooks[n].HookId == hook_id)
3682
0
            g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
3683
0
}
3684
3685
// Call context hooks (used by e.g. test engine)
3686
// We assume a small number of hooks so all stored in same array
3687
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
3688
206k
{
3689
206k
    ImGuiContext& g = *ctx;
3690
206k
    for (int n = 0; n < g.Hooks.Size; n++)
3691
0
        if (g.Hooks[n].Type == hook_type)
3692
0
            g.Hooks[n].Callback(&g, &g.Hooks[n]);
3693
206k
}
3694
3695
3696
//-----------------------------------------------------------------------------
3697
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
3698
//-----------------------------------------------------------------------------
3699
3700
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
3701
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
3702
3
{
3703
3
    memset(this, 0, sizeof(*this));
3704
3
    Name = ImStrdup(name);
3705
3
    NameBufLen = (int)strlen(name) + 1;
3706
3
    ID = ImHashStr(name);
3707
3
    IDStack.push_back(ID);
3708
3
    ViewportAllowPlatformMonitorExtend = -1;
3709
3
    ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
3710
3
    MoveId = GetID("#MOVE");
3711
3
    TabId = GetID("#TAB");
3712
3
    ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
3713
3
    ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
3714
3
    AutoFitFramesX = AutoFitFramesY = -1;
3715
3
    AutoPosLastDirection = ImGuiDir_None;
3716
3
    SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = 0;
3717
3
    SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
3718
3
    LastFrameActive = -1;
3719
3
    LastFrameJustFocused = -1;
3720
3
    LastTimeActive = -1.0f;
3721
3
    FontWindowScale = FontDpiScale = 1.0f;
3722
3
    SettingsOffset = -1;
3723
3
    DockOrder = -1;
3724
3
    DrawList = &DrawListInst;
3725
3
    DrawList->_Data = &context->DrawListSharedData;
3726
3
    DrawList->_OwnerName = Name;
3727
3
    IM_PLACEMENT_NEW(&WindowClass) ImGuiWindowClass();
3728
3
}
3729
3730
ImGuiWindow::~ImGuiWindow()
3731
0
{
3732
0
    IM_ASSERT(DrawList == &DrawListInst);
3733
0
    IM_DELETE(Name);
3734
0
    ColumnsStorage.clear_destruct();
3735
0
}
3736
3737
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
3738
79.6k
{
3739
79.6k
    ImGuiID seed = IDStack.back();
3740
79.6k
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
3741
79.6k
    ImGuiContext& g = *GImGui;
3742
79.6k
    if (g.DebugHookIdInfo == id)
3743
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
3744
79.6k
    return id;
3745
79.6k
}
3746
3747
ImGuiID ImGuiWindow::GetID(const void* ptr)
3748
0
{
3749
0
    ImGuiID seed = IDStack.back();
3750
0
    ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
3751
0
    ImGuiContext& g = *GImGui;
3752
0
    if (g.DebugHookIdInfo == id)
3753
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_Pointer, ptr, NULL);
3754
0
    return id;
3755
0
}
3756
3757
ImGuiID ImGuiWindow::GetID(int n)
3758
3.02k
{
3759
3.02k
    ImGuiID seed = IDStack.back();
3760
3.02k
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
3761
3.02k
    ImGuiContext& g = *GImGui;
3762
3.02k
    if (g.DebugHookIdInfo == id)
3763
0
        ImGui::DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
3764
3.02k
    return id;
3765
3.02k
}
3766
3767
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
3768
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
3769
0
{
3770
0
    ImGuiID seed = IDStack.back();
3771
0
    ImRect r_rel = ImGui::WindowRectAbsToRel(this, r_abs);
3772
0
    ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
3773
0
    return id;
3774
0
}
3775
3776
static void SetCurrentWindow(ImGuiWindow* window)
3777
143k
{
3778
143k
    ImGuiContext& g = *GImGui;
3779
143k
    g.CurrentWindow = window;
3780
143k
    g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
3781
143k
    if (window)
3782
109k
        g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
3783
143k
}
3784
3785
void ImGui::GcCompactTransientMiscBuffers()
3786
0
{
3787
0
    ImGuiContext& g = *GImGui;
3788
0
    g.ItemFlagsStack.clear();
3789
0
    g.GroupStack.clear();
3790
0
    TableGcCompactSettings();
3791
0
}
3792
3793
// Free up/compact internal window buffers, we can use this when a window becomes unused.
3794
// Not freed:
3795
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
3796
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
3797
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
3798
3
{
3799
3
    window->MemoryCompacted = true;
3800
3
    window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
3801
3
    window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
3802
3
    window->IDStack.clear();
3803
3
    window->DrawList->_ClearFreeMemory();
3804
3
    window->DC.ChildWindows.clear();
3805
3
    window->DC.ItemWidthStack.clear();
3806
3
    window->DC.TextWrapPosStack.clear();
3807
3
}
3808
3809
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
3810
2
{
3811
    // We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
3812
    // The other buffers tends to amortize much faster.
3813
2
    window->MemoryCompacted = false;
3814
2
    window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
3815
2
    window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
3816
2
    window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
3817
2
}
3818
3819
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
3820
389
{
3821
389
    ImGuiContext& g = *GImGui;
3822
3823
    // While most behaved code would make an effort to not steal active id during window move/drag operations,
3824
    // we at least need to be resilient to it. Cancelling the move is rather aggressive and users of 'master' branch
3825
    // may prefer the weird ill-defined half working situation ('docking' did assert), so may need to rework that.
3826
389
    if (g.MovingWindow != NULL && g.ActiveId == g.MovingWindow->MoveId)
3827
0
    {
3828
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() cancel MovingWindow\n");
3829
0
        g.MovingWindow = NULL;
3830
0
    }
3831
3832
    // Set active id
3833
389
    g.ActiveIdIsJustActivated = (g.ActiveId != id);
3834
389
    if (g.ActiveIdIsJustActivated)
3835
384
    {
3836
384
        IMGUI_DEBUG_LOG_ACTIVEID("SetActiveID() old:0x%08X (window \"%s\") -> new:0x%08X (window \"%s\")\n", g.ActiveId, g.ActiveIdWindow ? g.ActiveIdWindow->Name : "", id, window ? window->Name : "");
3837
384
        g.ActiveIdTimer = 0.0f;
3838
384
        g.ActiveIdHasBeenPressedBefore = false;
3839
384
        g.ActiveIdHasBeenEditedBefore = false;
3840
384
        g.ActiveIdMouseButton = -1;
3841
384
        if (id != 0)
3842
201
        {
3843
201
            g.LastActiveId = id;
3844
201
            g.LastActiveIdTimer = 0.0f;
3845
201
        }
3846
384
    }
3847
389
    g.ActiveId = id;
3848
389
    g.ActiveIdAllowOverlap = false;
3849
389
    g.ActiveIdNoClearOnFocusLoss = false;
3850
389
    g.ActiveIdWindow = window;
3851
389
    g.ActiveIdHasBeenEditedThisFrame = false;
3852
389
    if (id)
3853
201
    {
3854
201
        g.ActiveIdIsAlive = id;
3855
201
        g.ActiveIdSource = (g.NavActivateId == id || g.NavActivateInputId == id || g.NavJustMovedToId == id) ? (ImGuiInputSource)ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
3856
201
    }
3857
3858
    // Clear declaration of inputs claimed by the widget
3859
    // (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
3860
389
    g.ActiveIdUsingNavDirMask = 0x00;
3861
389
    g.ActiveIdUsingAllKeyboardKeys = false;
3862
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
3863
    g.ActiveIdUsingNavInputMask = 0x00;
3864
#endif
3865
389
}
3866
3867
void ImGui::ClearActiveID()
3868
188
{
3869
188
    SetActiveID(0, NULL); // g.ActiveId = 0;
3870
188
}
3871
3872
void ImGui::SetHoveredID(ImGuiID id)
3873
1.02k
{
3874
1.02k
    ImGuiContext& g = *GImGui;
3875
1.02k
    g.HoveredId = id;
3876
1.02k
    g.HoveredIdAllowOverlap = false;
3877
1.02k
    if (id != 0 && g.HoveredIdPreviousFrame != id)
3878
179
        g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
3879
1.02k
}
3880
3881
ImGuiID ImGui::GetHoveredID()
3882
0
{
3883
0
    ImGuiContext& g = *GImGui;
3884
0
    return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
3885
0
}
3886
3887
// This is called by ItemAdd().
3888
// Code not using ItemAdd() may need to call this manually otherwise ActiveId will be cleared. In IMGUI_VERSION_NUM < 18717 this was called by GetID().
3889
void ImGui::KeepAliveID(ImGuiID id)
3890
77.1k
{
3891
77.1k
    ImGuiContext& g = *GImGui;
3892
77.1k
    if (g.ActiveId == id)
3893
485
        g.ActiveIdIsAlive = id;
3894
77.1k
    if (g.ActiveIdPreviousFrame == id)
3895
467
        g.ActiveIdPreviousFrameIsAlive = true;
3896
77.1k
}
3897
3898
void ImGui::MarkItemEdited(ImGuiID id)
3899
0
{
3900
    // This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
3901
    // ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need to fill the data.
3902
0
    ImGuiContext& g = *GImGui;
3903
0
    IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
3904
0
    IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
3905
    //IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
3906
0
    g.ActiveIdHasBeenEditedThisFrame = true;
3907
0
    g.ActiveIdHasBeenEditedBefore = true;
3908
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
3909
0
}
3910
3911
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
3912
1.18k
{
3913
    // An active popup disable hovering on other windows (apart from its own children)
3914
    // FIXME-OPT: This could be cached/stored within the window.
3915
1.18k
    ImGuiContext& g = *GImGui;
3916
1.18k
    if (g.NavWindow)
3917
373
        if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindowDockTree)
3918
373
            if (focused_root_window->WasActive && focused_root_window != window->RootWindowDockTree)
3919
0
            {
3920
                // For the purpose of those flags we differentiate "standard popup" from "modal popup"
3921
                // NB: The 'else' is important because Modal windows are also Popups.
3922
0
                bool want_inhibit = false;
3923
0
                if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
3924
0
                    want_inhibit = true;
3925
0
                else if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
3926
0
                    want_inhibit = true;
3927
3928
                // Inhibit hover unless the window is within the stack of our modal/popup
3929
0
                if (want_inhibit)
3930
0
                    if (!ImGui::IsWindowWithinBeginStackOf(window->RootWindow, focused_root_window))
3931
0
                        return false;
3932
0
            }
3933
3934
    // Filter by viewport
3935
1.18k
    if (window->Viewport != g.MouseViewport)
3936
0
        if (g.MovingWindow == NULL || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree)
3937
0
            return false;
3938
3939
1.18k
    return true;
3940
1.18k
}
3941
3942
// This is roughly matching the behavior of internal-facing ItemHoverable()
3943
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
3944
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
3945
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
3946
0
{
3947
0
    ImGuiContext& g = *GImGui;
3948
0
    ImGuiWindow* window = g.CurrentWindow;
3949
0
    if (g.NavDisableMouseHover && !g.NavDisableHighlight && !(flags & ImGuiHoveredFlags_NoNavOverride))
3950
0
    {
3951
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3952
0
            return false;
3953
0
        if (!IsItemFocused())
3954
0
            return false;
3955
0
    }
3956
0
    else
3957
0
    {
3958
        // Test for bounding box overlap, as updated as ItemAdd()
3959
0
        ImGuiItemStatusFlags status_flags = g.LastItemData.StatusFlags;
3960
0
        if (!(status_flags & ImGuiItemStatusFlags_HoveredRect))
3961
0
            return false;
3962
0
        IM_ASSERT((flags & (ImGuiHoveredFlags_AnyWindow | ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows | ImGuiHoveredFlags_NoPopupHierarchy | ImGuiHoveredFlags_DockHierarchy)) == 0);   // Flags not supported by this function
3963
3964
        // Done with rectangle culling so we can perform heavier checks now
3965
        // Test if we are hovering the right window (our window could be behind another window)
3966
        // [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
3967
        // [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable
3968
        // to use IsItemHovered() after EndChild() itself. Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was
3969
        // the test that has been running for a long while.
3970
0
        if (g.HoveredWindow != window && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
3971
0
            if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
3972
0
                return false;
3973
3974
        // Test if another item is active (e.g. being dragged)
3975
0
        if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
3976
0
            if (g.ActiveId != 0 && g.ActiveId != g.LastItemData.ID && !g.ActiveIdAllowOverlap)
3977
0
                if (g.ActiveId != window->MoveId && g.ActiveId != window->TabId)
3978
0
                    return false;
3979
3980
        // Test if interactions on this window are blocked by an active popup or modal.
3981
        // The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
3982
0
        if (!IsWindowContentHoverable(window, flags) && !(g.LastItemData.InFlags & ImGuiItemFlags_NoWindowHoverableCheck))
3983
0
            return false;
3984
3985
        // Test if the item is disabled
3986
0
        if ((g.LastItemData.InFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
3987
0
            return false;
3988
3989
        // Special handling for calling after Begin() which represent the title bar or tab.
3990
        // When the window is skipped/collapsed (SkipItems==true) that last item (always ->MoveId submitted by Begin)
3991
        // will never be overwritten so we need to detect the case.
3992
0
        if (g.LastItemData.ID == window->MoveId && window->WriteAccessed)
3993
0
            return false;
3994
0
    }
3995
3996
    // Handle hover delay
3997
    // (some ideas: https://www.nngroup.com/articles/timing-exposing-content)
3998
0
    float delay;
3999
0
    if (flags & ImGuiHoveredFlags_DelayNormal)
4000
0
        delay = g.IO.HoverDelayNormal;
4001
0
    else if (flags & ImGuiHoveredFlags_DelayShort)
4002
0
        delay = g.IO.HoverDelayShort;
4003
0
    else
4004
0
        delay = 0.0f;
4005
0
    if (delay > 0.0f)
4006
0
    {
4007
0
        ImGuiID hover_delay_id = (g.LastItemData.ID != 0) ? g.LastItemData.ID : window->GetIDFromRectangle(g.LastItemData.Rect);
4008
0
        if ((flags & ImGuiHoveredFlags_NoSharedDelay) && (g.HoverDelayIdPreviousFrame != hover_delay_id))
4009
0
            g.HoverDelayTimer = 0.0f;
4010
0
        g.HoverDelayId = hover_delay_id;
4011
0
        return g.HoverDelayTimer >= delay;
4012
0
    }
4013
4014
0
    return true;
4015
0
}
4016
4017
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
4018
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
4019
75.2k
{
4020
75.2k
    ImGuiContext& g = *GImGui;
4021
75.2k
    if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
4022
454
        return false;
4023
4024
74.7k
    ImGuiWindow* window = g.CurrentWindow;
4025
74.7k
    if (g.HoveredWindow != window)
4026
73.0k
        return false;
4027
1.73k
    if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
4028
273
        return false;
4029
1.45k
    if (!IsMouseHoveringRect(bb.Min, bb.Max))
4030
433
        return false;
4031
4032
    // Done with rectangle culling so we can perform heavier checks now.
4033
1.02k
    ImGuiItemFlags item_flags = (g.LastItemData.ID == id ? g.LastItemData.InFlags : g.CurrentItemFlags);
4034
1.02k
    if (!(item_flags & ImGuiItemFlags_NoWindowHoverableCheck) && !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
4035
0
    {
4036
0
        g.HoveredIdDisabled = true;
4037
0
        return false;
4038
0
    }
4039
4040
    // We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
4041
    // hover test in widgets code. We could also decide to split this function is two.
4042
1.02k
    if (id != 0)
4043
1.02k
        SetHoveredID(id);
4044
4045
    // When disabled we'll return false but still set HoveredId
4046
1.02k
    if (item_flags & ImGuiItemFlags_Disabled)
4047
0
    {
4048
        // Release active id if turning disabled
4049
0
        if (g.ActiveId == id)
4050
0
            ClearActiveID();
4051
0
        g.HoveredIdDisabled = true;
4052
0
        return false;
4053
0
    }
4054
4055
1.02k
    if (id != 0)
4056
1.02k
    {
4057
        // [DEBUG] Item Picker tool!
4058
        // We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
4059
        // the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
4060
        // items if we performed the test in ItemAdd(), but that would incur a small runtime cost.
4061
1.02k
        if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
4062
0
            GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
4063
1.02k
        if (g.DebugItemPickerBreakId == id)
4064
0
            IM_DEBUG_BREAK();
4065
1.02k
    }
4066
4067
1.02k
    if (g.NavDisableMouseHover)
4068
14
        return false;
4069
4070
1.01k
    return true;
4071
1.02k
}
4072
4073
// FIXME: This is inlined/duplicated in ItemAdd()
4074
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id)
4075
0
{
4076
0
    ImGuiContext& g = *GImGui;
4077
0
    ImGuiWindow* window = g.CurrentWindow;
4078
0
    if (!bb.Overlaps(window->ClipRect))
4079
0
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
4080
0
            if (!g.LogEnabled)
4081
0
                return true;
4082
0
    return false;
4083
0
}
4084
4085
// This is also inlined in ItemAdd()
4086
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
4087
void ImGui::SetLastItemData(ImGuiID item_id, ImGuiItemFlags in_flags, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
4088
71.9k
{
4089
71.9k
    ImGuiContext& g = *GImGui;
4090
71.9k
    g.LastItemData.ID = item_id;
4091
71.9k
    g.LastItemData.InFlags = in_flags;
4092
71.9k
    g.LastItemData.StatusFlags = item_flags;
4093
71.9k
    g.LastItemData.Rect = item_rect;
4094
71.9k
}
4095
4096
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
4097
0
{
4098
0
    if (wrap_pos_x < 0.0f)
4099
0
        return 0.0f;
4100
4101
0
    ImGuiContext& g = *GImGui;
4102
0
    ImGuiWindow* window = g.CurrentWindow;
4103
0
    if (wrap_pos_x == 0.0f)
4104
0
    {
4105
        // We could decide to setup a default wrapping max point for auto-resizing windows,
4106
        // or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
4107
        //if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
4108
        //    wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
4109
        //else
4110
0
        wrap_pos_x = window->WorkRect.Max.x;
4111
0
    }
4112
0
    else if (wrap_pos_x > 0.0f)
4113
0
    {
4114
0
        wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
4115
0
    }
4116
4117
0
    return ImMax(wrap_pos_x - pos.x, 1.0f);
4118
0
}
4119
4120
// IM_ALLOC() == ImGui::MemAlloc()
4121
void* ImGui::MemAlloc(size_t size)
4122
1.22k
{
4123
1.22k
    if (ImGuiContext* ctx = GImGui)
4124
1.22k
        ctx->IO.MetricsActiveAllocations++;
4125
1.22k
    return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
4126
1.22k
}
4127
4128
// IM_FREE() == ImGui::MemFree()
4129
void ImGui::MemFree(void* ptr)
4130
1.17k
{
4131
1.17k
    if (ptr)
4132
1.17k
        if (ImGuiContext* ctx = GImGui)
4133
1.17k
            ctx->IO.MetricsActiveAllocations--;
4134
1.17k
    return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
4135
1.17k
}
4136
4137
const char* ImGui::GetClipboardText()
4138
0
{
4139
0
    ImGuiContext& g = *GImGui;
4140
0
    return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
4141
0
}
4142
4143
void ImGui::SetClipboardText(const char* text)
4144
0
{
4145
0
    ImGuiContext& g = *GImGui;
4146
0
    if (g.IO.SetClipboardTextFn)
4147
0
        g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
4148
0
}
4149
4150
const char* ImGui::GetVersion()
4151
0
{
4152
0
    return IMGUI_VERSION;
4153
0
}
4154
4155
ImGuiIO& ImGui::GetIO()
4156
110k
{
4157
110k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4158
110k
    return GImGui->IO;
4159
110k
}
4160
4161
ImGuiPlatformIO& ImGui::GetPlatformIO()
4162
0
{
4163
0
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
4164
0
    return GImGui->PlatformIO;
4165
0
}
4166
4167
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
4168
ImDrawData* ImGui::GetDrawData()
4169
34.4k
{
4170
34.4k
    ImGuiContext& g = *GImGui;
4171
34.4k
    ImGuiViewportP* viewport = g.Viewports[0];
4172
34.4k
    return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
4173
34.4k
}
4174
4175
double ImGui::GetTime()
4176
70
{
4177
70
    return GImGui->Time;
4178
70
}
4179
4180
int ImGui::GetFrameCount()
4181
0
{
4182
0
    return GImGui->FrameCount;
4183
0
}
4184
4185
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
4186
0
{
4187
    // Create the draw list on demand, because they are not frequently used for all viewports
4188
0
    ImGuiContext& g = *GImGui;
4189
0
    IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
4190
0
    ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
4191
0
    if (draw_list == NULL)
4192
0
    {
4193
0
        draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
4194
0
        draw_list->_OwnerName = drawlist_name;
4195
0
        viewport->DrawLists[drawlist_no] = draw_list;
4196
0
    }
4197
4198
    // Our ImDrawList system requires that there is always a command
4199
0
    if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
4200
0
    {
4201
0
        draw_list->_ResetForNewFrame();
4202
0
        draw_list->PushTextureID(g.IO.Fonts->TexID);
4203
0
        draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
4204
0
        viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
4205
0
    }
4206
0
    return draw_list;
4207
0
}
4208
4209
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
4210
0
{
4211
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
4212
0
}
4213
4214
ImDrawList* ImGui::GetBackgroundDrawList()
4215
0
{
4216
0
    ImGuiContext& g = *GImGui;
4217
0
    return GetBackgroundDrawList(g.CurrentWindow->Viewport);
4218
0
}
4219
4220
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
4221
0
{
4222
0
    return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
4223
0
}
4224
4225
ImDrawList* ImGui::GetForegroundDrawList()
4226
0
{
4227
0
    ImGuiContext& g = *GImGui;
4228
0
    return GetForegroundDrawList(g.CurrentWindow->Viewport);
4229
0
}
4230
4231
ImDrawListSharedData* ImGui::GetDrawListSharedData()
4232
0
{
4233
0
    return &GImGui->DrawListSharedData;
4234
0
}
4235
4236
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
4237
44
{
4238
    // Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
4239
    // We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
4240
    // This is because we want ActiveId to be set even when the window is not permitted to move.
4241
44
    ImGuiContext& g = *GImGui;
4242
44
    FocusWindow(window);
4243
44
    SetActiveID(window->MoveId, window);
4244
44
    g.NavDisableHighlight = true;
4245
44
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - window->RootWindowDockTree->Pos;
4246
44
    g.ActiveIdNoClearOnFocusLoss = true;
4247
44
    SetActiveIdUsingAllKeyboardKeys();
4248
4249
44
    bool can_move_window = true;
4250
44
    if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoMove))
4251
10
        can_move_window = false;
4252
44
    if (ImGuiDockNode* node = window->DockNodeAsHost)
4253
0
        if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
4254
0
            can_move_window = false;
4255
44
    if (can_move_window)
4256
34
        g.MovingWindow = window;
4257
44
}
4258
4259
// We use 'undock_floating_node == false' when dragging from title bar to allow moving groups of floating nodes without undocking them.
4260
// - undock_floating_node == true: when dragging from a floating node within a hierarchy, always undock the node.
4261
// - undock_floating_node == false: when dragging from a floating node within a hierarchy, move root window.
4262
void ImGui::StartMouseMovingWindowOrNode(ImGuiWindow* window, ImGuiDockNode* node, bool undock_floating_node)
4263
18
{
4264
18
    ImGuiContext& g = *GImGui;
4265
18
    bool can_undock_node = false;
4266
18
    if (node != NULL && node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove) == 0)
4267
0
    {
4268
        // Can undock if:
4269
        // - part of a floating node hierarchy with more than one visible node (if only one is visible, we'll just move the whole hierarchy)
4270
        // - part of a dockspace node hierarchy (trivia: undocking from a fixed/central node will create a new node and copy windows)
4271
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
4272
0
        if (root_node->OnlyNodeWithWindows != node || root_node->CentralNode != NULL)   // -V1051 PVS-Studio thinks node should be root_node and is wrong about that.
4273
0
            if (undock_floating_node || root_node->IsDockSpace())
4274
0
                can_undock_node = true;
4275
0
    }
4276
4277
18
    const bool clicked = IsMouseClicked(0);
4278
18
    const bool dragging = IsMouseDragging(0, g.IO.MouseDragThreshold * 1.70f);
4279
18
    if (can_undock_node && dragging)
4280
0
        DockContextQueueUndockNode(&g, node); // Will lead to DockNodeStartMouseMovingWindow() -> StartMouseMovingWindow() being called next frame
4281
18
    else if (!can_undock_node && (clicked || dragging) && g.MovingWindow != window)
4282
18
        StartMouseMovingWindow(window);
4283
18
}
4284
4285
// Handle mouse moving window
4286
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
4287
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
4288
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
4289
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
4290
void ImGui::UpdateMouseMovingWindowNewFrame()
4291
34.4k
{
4292
34.4k
    ImGuiContext& g = *GImGui;
4293
34.4k
    if (g.MovingWindow != NULL)
4294
136
    {
4295
        // We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
4296
        // We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
4297
136
        KeepAliveID(g.ActiveId);
4298
136
        IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindowDockTree);
4299
136
        ImGuiWindow* moving_window = g.MovingWindow->RootWindowDockTree;
4300
4301
        // When a window stop being submitted while being dragged, it may will its viewport until next Begin()
4302
136
        const bool window_disappared = ((!moving_window->WasActive && !moving_window->Active) || moving_window->Viewport == NULL);
4303
136
        if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos) && !window_disappared)
4304
102
        {
4305
102
            ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
4306
102
            if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
4307
66
            {
4308
66
                SetWindowPos(moving_window, pos, ImGuiCond_Always);
4309
66
                if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
4310
0
                {
4311
0
                    moving_window->Viewport->Pos = pos;
4312
0
                    moving_window->Viewport->UpdateWorkRect();
4313
0
                }
4314
66
            }
4315
102
            FocusWindow(g.MovingWindow);
4316
102
        }
4317
34
        else
4318
34
        {
4319
34
            if (!window_disappared)
4320
34
            {
4321
                // Try to merge the window back into the main viewport.
4322
                // This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
4323
34
                if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
4324
0
                    UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
4325
4326
                // Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
4327
34
                if (!IsDragDropPayloadBeingAccepted())
4328
34
                    g.MouseViewport = moving_window->Viewport;
4329
4330
                // Clear the NoInput window flag set by the Viewport system
4331
34
                moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs; // FIXME-VIEWPORT: Test engine managed to crash here because Viewport was NULL.
4332
34
            }
4333
4334
34
            g.MovingWindow = NULL;
4335
34
            ClearActiveID();
4336
34
        }
4337
136
    }
4338
34.3k
    else
4339
34.3k
    {
4340
        // When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
4341
34.3k
        if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
4342
25
        {
4343
25
            KeepAliveID(g.ActiveId);
4344
25
            if (!g.IO.MouseDown[0])
4345
10
                ClearActiveID();
4346
25
        }
4347
34.3k
    }
4348
34.4k
}
4349
4350
// Initiate moving window when clicking on empty space or title bar.
4351
// Handle left-click and right-click focus.
4352
void ImGui::UpdateMouseMovingWindowEndFrame()
4353
34.4k
{
4354
34.4k
    ImGuiContext& g = *GImGui;
4355
34.4k
    if (g.ActiveId != 0 || g.HoveredId != 0)
4356
1.24k
        return;
4357
4358
    // Unless we just made a window/popup appear
4359
33.2k
    if (g.NavWindow && g.NavWindow->Appearing)
4360
3
        return;
4361
4362
    // Click on empty space to focus window and start moving
4363
    // (after we're done with all our widgets, so e.g. clicking on docking tab-bar which have set HoveredId already and not get us here!)
4364
33.2k
    if (g.IO.MouseClicked[0])
4365
1.55k
    {
4366
        // Handle the edge case of a popup being closed while clicking in its empty space.
4367
        // If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
4368
1.55k
        ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
4369
1.55k
        const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
4370
4371
1.55k
        if (root_window != NULL && !is_closed_popup)
4372
26
        {
4373
26
            StartMouseMovingWindow(g.HoveredWindow); //-V595
4374
4375
            // Cancel moving if clicked outside of title bar
4376
26
            if (g.IO.ConfigWindowsMoveFromTitleBarOnly)
4377
0
                if (!(root_window->Flags & ImGuiWindowFlags_NoTitleBar) || root_window->DockIsActive)
4378
0
                    if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
4379
0
                        g.MovingWindow = NULL;
4380
4381
            // Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
4382
26
            if (g.HoveredIdDisabled)
4383
0
                g.MovingWindow = NULL;
4384
26
        }
4385
1.53k
        else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
4386
68
        {
4387
            // Clicking on void disable focus
4388
68
            FocusWindow(NULL);
4389
68
        }
4390
1.55k
    }
4391
4392
    // With right mouse button we close popups without changing focus based on where the mouse is aimed
4393
    // Instead, focus will be restored to the window under the bottom-most closed popup.
4394
    // (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
4395
33.2k
    if (g.IO.MouseClicked[1])
4396
271
    {
4397
        // Find the top-most window between HoveredWindow and the top-most Modal Window.
4398
        // This is where we can trim the popup stack.
4399
271
        ImGuiWindow* modal = GetTopMostPopupModal();
4400
271
        bool hovered_window_above_modal = g.HoveredWindow && (modal == NULL || IsWindowAbove(g.HoveredWindow, modal));
4401
271
        ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
4402
271
    }
4403
33.2k
}
4404
4405
// This is called during NewFrame()->UpdateViewportsNewFrame() only.
4406
// Need to keep in sync with SetWindowPos()
4407
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
4408
0
{
4409
0
    window->Pos += delta;
4410
0
    window->ClipRect.Translate(delta);
4411
0
    window->OuterRectClipped.Translate(delta);
4412
0
    window->InnerRect.Translate(delta);
4413
0
    window->DC.CursorPos += delta;
4414
0
    window->DC.CursorStartPos += delta;
4415
0
    window->DC.CursorMaxPos += delta;
4416
0
    window->DC.IdealMaxPos += delta;
4417
0
}
4418
4419
static void ScaleWindow(ImGuiWindow* window, float scale)
4420
0
{
4421
0
    ImVec2 origin = window->Viewport->Pos;
4422
0
    window->Pos = ImFloor((window->Pos - origin) * scale + origin);
4423
0
    window->Size = ImFloor(window->Size * scale);
4424
0
    window->SizeFull = ImFloor(window->SizeFull * scale);
4425
0
    window->ContentSize = ImFloor(window->ContentSize * scale);
4426
0
}
4427
4428
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
4429
106k
{
4430
106k
    return (window->Active) && (!window->Hidden);
4431
106k
}
4432
4433
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
4434
void ImGui::UpdateHoveredWindowAndCaptureFlags()
4435
34.4k
{
4436
34.4k
    ImGuiContext& g = *GImGui;
4437
34.4k
    ImGuiIO& io = g.IO;
4438
34.4k
    g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
4439
4440
    // Find the window hovered by mouse:
4441
    // - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
4442
    // - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
4443
    // - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
4444
34.4k
    bool clear_hovered_windows = false;
4445
34.4k
    FindHoveredWindow();
4446
34.4k
    IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
4447
4448
    // Modal windows prevents mouse from hovering behind them.
4449
34.4k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
4450
34.4k
    if (modal_window && g.HoveredWindow && !IsWindowWithinBeginStackOf(g.HoveredWindow->RootWindow, modal_window)) // FIXME-MERGE: RootWindowDockTree ?
4451
0
        clear_hovered_windows = true;
4452
4453
    // Disabled mouse?
4454
34.4k
    if (io.ConfigFlags & ImGuiConfigFlags_NoMouse)
4455
0
        clear_hovered_windows = true;
4456
4457
    // We track click ownership. When clicked outside of a window the click is owned by the application and
4458
    // won't report hovering nor request capture even while dragging over our windows afterward.
4459
34.4k
    const bool has_open_popup = (g.OpenPopupStack.Size > 0);
4460
34.4k
    const bool has_open_modal = (modal_window != NULL);
4461
34.4k
    int mouse_earliest_down = -1;
4462
34.4k
    bool mouse_any_down = false;
4463
206k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
4464
172k
    {
4465
172k
        if (io.MouseClicked[i])
4466
2.92k
        {
4467
2.92k
            io.MouseDownOwned[i] = (g.HoveredWindow != NULL) || has_open_popup;
4468
2.92k
            io.MouseDownOwnedUnlessPopupClose[i] = (g.HoveredWindow != NULL) || has_open_modal;
4469
2.92k
        }
4470
172k
        mouse_any_down |= io.MouseDown[i];
4471
172k
        if (io.MouseDown[i])
4472
19.7k
            if (mouse_earliest_down == -1 || io.MouseClickedTime[i] < io.MouseClickedTime[mouse_earliest_down])
4473
13.6k
                mouse_earliest_down = i;
4474
172k
    }
4475
34.4k
    const bool mouse_avail = (mouse_earliest_down == -1) || io.MouseDownOwned[mouse_earliest_down];
4476
34.4k
    const bool mouse_avail_unless_popup_close = (mouse_earliest_down == -1) || io.MouseDownOwnedUnlessPopupClose[mouse_earliest_down];
4477
4478
    // If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
4479
    // FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
4480
34.4k
    const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
4481
34.4k
    if (!mouse_avail && !mouse_dragging_extern_payload)
4482
11.0k
        clear_hovered_windows = true;
4483
4484
34.4k
    if (clear_hovered_windows)
4485
11.0k
        g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
4486
4487
    // Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui only, false = dispatch mouse to Dear ImGui + underlying app)
4488
    // Update io.WantCaptureMouseAllowPopupClose (experimental) to give a chance for app to react to popup closure with a drag
4489
34.4k
    if (g.WantCaptureMouseNextFrame != -1)
4490
0
    {
4491
0
        io.WantCaptureMouse = io.WantCaptureMouseUnlessPopupClose = (g.WantCaptureMouseNextFrame != 0);
4492
0
    }
4493
34.4k
    else
4494
34.4k
    {
4495
34.4k
        io.WantCaptureMouse = (mouse_avail && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_popup;
4496
34.4k
        io.WantCaptureMouseUnlessPopupClose = (mouse_avail_unless_popup_close && (g.HoveredWindow != NULL || mouse_any_down)) || has_open_modal;
4497
34.4k
    }
4498
4499
    // Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui only, false = dispatch keyboard info to Dear ImGui + underlying app)
4500
34.4k
    if (g.WantCaptureKeyboardNextFrame != -1)
4501
0
        io.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
4502
34.4k
    else
4503
34.4k
        io.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
4504
34.4k
    if (io.NavActive && (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(io.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
4505
1.31k
        io.WantCaptureKeyboard = true;
4506
4507
    // Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
4508
34.4k
    io.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
4509
34.4k
}
4510
4511
void ImGui::NewFrame()
4512
34.4k
{
4513
34.4k
    IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
4514
34.4k
    ImGuiContext& g = *GImGui;
4515
4516
    // Remove pending delete hooks before frame start.
4517
    // This deferred removal avoid issues of removal while iterating the hook vector
4518
34.4k
    for (int n = g.Hooks.Size - 1; n >= 0; n--)
4519
0
        if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
4520
0
            g.Hooks.erase(&g.Hooks[n]);
4521
4522
34.4k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
4523
4524
    // Check and assert for various common IO and Configuration mistakes
4525
34.4k
    g.ConfigFlagsLastFrame = g.ConfigFlagsCurrFrame;
4526
34.4k
    ErrorCheckNewFrameSanityChecks();
4527
34.4k
    g.ConfigFlagsCurrFrame = g.IO.ConfigFlags;
4528
4529
    // Load settings on first frame, save settings when modified (after a delay)
4530
34.4k
    UpdateSettings();
4531
4532
34.4k
    g.Time += g.IO.DeltaTime;
4533
34.4k
    g.WithinFrameScope = true;
4534
34.4k
    g.FrameCount += 1;
4535
34.4k
    g.TooltipOverrideCount = 0;
4536
34.4k
    g.WindowsActiveCount = 0;
4537
34.4k
    g.MenusIdSubmittedThisFrame.resize(0);
4538
4539
    // Calculate frame-rate for the user, as a purely luxurious feature
4540
34.4k
    g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
4541
34.4k
    g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
4542
34.4k
    g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
4543
34.4k
    g.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
4544
34.4k
    g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
4545
4546
    // Process input queue (trickle as many events as possible), turn events into writes to IO structure
4547
34.4k
    g.InputEventsTrail.resize(0);
4548
34.4k
    UpdateInputEvents(g.IO.ConfigInputTrickleEventQueue);
4549
4550
    // Update viewports (after processing input queue, so io.MouseHoveredViewport is set)
4551
34.4k
    UpdateViewportsNewFrame();
4552
4553
    // Setup current font and draw list shared data
4554
    // FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
4555
34.4k
    g.IO.Fonts->Locked = true;
4556
34.4k
    SetCurrentFont(GetDefaultFont());
4557
34.4k
    IM_ASSERT(g.Font->IsLoaded());
4558
34.4k
    ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
4559
68.8k
    for (int n = 0; n < g.Viewports.Size; n++)
4560
34.4k
        virtual_space.Add(g.Viewports[n]->GetMainRect());
4561
34.4k
    g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
4562
34.4k
    g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
4563
34.4k
    g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
4564
34.4k
    g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
4565
34.4k
    if (g.Style.AntiAliasedLines)
4566
34.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
4567
34.4k
    if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
4568
34.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
4569
34.4k
    if (g.Style.AntiAliasedFill)
4570
34.4k
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
4571
34.4k
    if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
4572
0
        g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
4573
4574
    // Mark rendering data as invalid to prevent user who may have a handle on it to use it.
4575
68.8k
    for (int n = 0; n < g.Viewports.Size; n++)
4576
34.4k
    {
4577
34.4k
        ImGuiViewportP* viewport = g.Viewports[n];
4578
34.4k
        viewport->DrawData = NULL;
4579
34.4k
        viewport->DrawDataP.Clear();
4580
34.4k
    }
4581
4582
    // Drag and drop keep the source ID alive so even if the source disappear our state is consistent
4583
34.4k
    if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
4584
77
        KeepAliveID(g.DragDropPayload.SourceId);
4585
4586
    // Update HoveredId data
4587
34.4k
    if (!g.HoveredIdPreviousFrame)
4588
33.4k
        g.HoveredIdTimer = 0.0f;
4589
34.4k
    if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
4590
33.5k
        g.HoveredIdNotActiveTimer = 0.0f;
4591
34.4k
    if (g.HoveredId)
4592
1.02k
        g.HoveredIdTimer += g.IO.DeltaTime;
4593
34.4k
    if (g.HoveredId && g.ActiveId != g.HoveredId)
4594
828
        g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
4595
34.4k
    g.HoveredIdPreviousFrame = g.HoveredId;
4596
34.4k
    g.HoveredId = 0;
4597
34.4k
    g.HoveredIdAllowOverlap = false;
4598
34.4k
    g.HoveredIdDisabled = false;
4599
4600
    // Clear ActiveID if the item is not alive anymore.
4601
    // In 1.87, the common most call to KeepAliveID() was moved from GetID() to ItemAdd().
4602
    // As a result, custom widget using ButtonBehavior() _without_ ItemAdd() need to call KeepAliveID() themselves.
4603
34.4k
    if (g.ActiveId != 0 && g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId)
4604
0
    {
4605
0
        IMGUI_DEBUG_LOG_ACTIVEID("NewFrame(): ClearActiveID() because it isn't marked alive anymore!\n");
4606
0
        ClearActiveID();
4607
0
    }
4608
4609
    // Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
4610
34.4k
    if (g.ActiveId)
4611
408
        g.ActiveIdTimer += g.IO.DeltaTime;
4612
34.4k
    g.LastActiveIdTimer += g.IO.DeltaTime;
4613
34.4k
    g.ActiveIdPreviousFrame = g.ActiveId;
4614
34.4k
    g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
4615
34.4k
    g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
4616
34.4k
    g.ActiveIdIsAlive = 0;
4617
34.4k
    g.ActiveIdHasBeenEditedThisFrame = false;
4618
34.4k
    g.ActiveIdPreviousFrameIsAlive = false;
4619
34.4k
    g.ActiveIdIsJustActivated = false;
4620
34.4k
    if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
4621
0
        g.TempInputId = 0;
4622
34.4k
    if (g.ActiveId == 0)
4623
34.0k
    {
4624
34.0k
        g.ActiveIdUsingNavDirMask = 0x00;
4625
34.0k
        g.ActiveIdUsingAllKeyboardKeys = false;
4626
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4627
        g.ActiveIdUsingNavInputMask = 0x00;
4628
#endif
4629
34.0k
    }
4630
4631
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
4632
    if (g.ActiveId == 0)
4633
        g.ActiveIdUsingNavInputMask = 0;
4634
    else if (g.ActiveIdUsingNavInputMask != 0)
4635
    {
4636
        // If your custom widget code used:                 { g.ActiveIdUsingNavInputMask |= (1 << ImGuiNavInput_Cancel); }
4637
        // Since IMGUI_VERSION_NUM >= 18804 it should be:   { SetKeyOwner(ImGuiKey_Escape, g.ActiveId); SetKeyOwner(ImGuiKey_NavGamepadCancel, g.ActiveId); }
4638
        if (g.ActiveIdUsingNavInputMask & (1 << ImGuiNavInput_Cancel))
4639
            SetKeyOwner(ImGuiKey_Escape, g.ActiveId);
4640
        if (g.ActiveIdUsingNavInputMask & ~(1 << ImGuiNavInput_Cancel))
4641
            IM_ASSERT(0); // Other values unsupported
4642
    }
4643
#endif
4644
4645
    // Update hover delay for IsItemHovered() with delays and tooltips
4646
34.4k
    g.HoverDelayIdPreviousFrame = g.HoverDelayId;
4647
34.4k
    if (g.HoverDelayId != 0)
4648
0
    {
4649
        //if (g.IO.MouseDelta.x == 0.0f && g.IO.MouseDelta.y == 0.0f) // Need design/flags
4650
0
        g.HoverDelayTimer += g.IO.DeltaTime;
4651
0
        g.HoverDelayClearTimer = 0.0f;
4652
0
        g.HoverDelayId = 0;
4653
0
    }
4654
34.4k
    else if (g.HoverDelayTimer > 0.0f)
4655
0
    {
4656
        // This gives a little bit of leeway before clearing the hover timer, allowing mouse to cross gaps
4657
0
        g.HoverDelayClearTimer += g.IO.DeltaTime;
4658
0
        if (g.HoverDelayClearTimer >= ImMax(0.20f, g.IO.DeltaTime * 2.0f)) // ~6 frames at 30 Hz + allow for low framerate
4659
0
            g.HoverDelayTimer = g.HoverDelayClearTimer = 0.0f; // May want a decaying timer, in which case need to clamp at max first, based on max of caller last requested timer.
4660
0
    }
4661
4662
    // Drag and drop
4663
34.4k
    g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
4664
34.4k
    g.DragDropAcceptIdCurr = 0;
4665
34.4k
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
4666
34.4k
    g.DragDropWithinSource = false;
4667
34.4k
    g.DragDropWithinTarget = false;
4668
34.4k
    g.DragDropHoldJustPressedId = 0;
4669
4670
    // Close popups on focus lost (currently wip/opt-in)
4671
    //if (g.IO.AppFocusLost)
4672
    //    ClosePopupsExceptModals();
4673
4674
    // Update keyboard input state
4675
34.4k
    UpdateKeyboardInputs();
4676
4677
    //IM_ASSERT(g.IO.KeyCtrl == IsKeyDown(ImGuiKey_LeftCtrl) || IsKeyDown(ImGuiKey_RightCtrl));
4678
    //IM_ASSERT(g.IO.KeyShift == IsKeyDown(ImGuiKey_LeftShift) || IsKeyDown(ImGuiKey_RightShift));
4679
    //IM_ASSERT(g.IO.KeyAlt == IsKeyDown(ImGuiKey_LeftAlt) || IsKeyDown(ImGuiKey_RightAlt));
4680
    //IM_ASSERT(g.IO.KeySuper == IsKeyDown(ImGuiKey_LeftSuper) || IsKeyDown(ImGuiKey_RightSuper));
4681
4682
    // Update gamepad/keyboard navigation
4683
34.4k
    NavUpdate();
4684
4685
    // Update mouse input state
4686
34.4k
    UpdateMouseInputs();
4687
4688
    // Undocking
4689
    // (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
4690
34.4k
    DockContextNewFrameUpdateUndocking(&g);
4691
4692
    // Find hovered window
4693
    // (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
4694
34.4k
    UpdateHoveredWindowAndCaptureFlags();
4695
4696
    // Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
4697
34.4k
    UpdateMouseMovingWindowNewFrame();
4698
4699
    // Background darkening/whitening
4700
34.4k
    if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
4701
0
        g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
4702
34.4k
    else
4703
34.4k
        g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
4704
4705
34.4k
    g.MouseCursor = ImGuiMouseCursor_Arrow;
4706
34.4k
    g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
4707
4708
    // Platform IME data: reset for the frame
4709
34.4k
    g.PlatformImeDataPrev = g.PlatformImeData;
4710
34.4k
    g.PlatformImeData.WantVisible = false;
4711
4712
    // Mouse wheel scrolling, scale
4713
34.4k
    UpdateMouseWheel();
4714
4715
    // Mark all windows as not visible and compact unused memory.
4716
34.4k
    IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
4717
34.4k
    const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
4718
137k
    for (int i = 0; i != g.Windows.Size; i++)
4719
103k
    {
4720
103k
        ImGuiWindow* window = g.Windows[i];
4721
103k
        window->WasActive = window->Active;
4722
103k
        window->Active = false;
4723
103k
        window->WriteAccessed = false;
4724
103k
        window->BeginCountPreviousFrame = window->BeginCount;
4725
103k
        window->BeginCount = 0;
4726
4727
        // Garbage collect transient buffers of recently unused windows
4728
103k
        if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
4729
3
            GcCompactTransientWindowBuffers(window);
4730
103k
    }
4731
4732
    // Garbage collect transient buffers of recently unused tables
4733
34.4k
    for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
4734
0
        if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
4735
0
            TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
4736
34.4k
    for (int i = 0; i < g.TablesTempData.Size; i++)
4737
0
        if (g.TablesTempData[i].LastTimeActive >= 0.0f && g.TablesTempData[i].LastTimeActive < memory_compact_start_time)
4738
0
            TableGcCompactTransientBuffers(&g.TablesTempData[i]);
4739
34.4k
    if (g.GcCompactAll)
4740
0
        GcCompactTransientMiscBuffers();
4741
34.4k
    g.GcCompactAll = false;
4742
4743
    // Closing the focused window restore focus to the first active root window in descending z-order
4744
34.4k
    if (g.NavWindow && !g.NavWindow->WasActive)
4745
0
        FocusTopMostWindowUnderOne(NULL, NULL);
4746
4747
    // No window should be open at the beginning of the frame.
4748
    // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
4749
34.4k
    g.CurrentWindowStack.resize(0);
4750
34.4k
    g.BeginPopupStack.resize(0);
4751
34.4k
    g.ItemFlagsStack.resize(0);
4752
34.4k
    g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
4753
34.4k
    g.GroupStack.resize(0);
4754
4755
    // Docking
4756
34.4k
    DockContextNewFrameUpdateDocking(&g);
4757
4758
    // [DEBUG] Update debug features
4759
34.4k
    UpdateDebugToolItemPicker();
4760
34.4k
    UpdateDebugToolStackQueries();
4761
34.4k
    if (g.DebugLocateFrames > 0 && --g.DebugLocateFrames == 0)
4762
0
        g.DebugLocateId = 0;
4763
4764
    // Create implicit/fallback window - which we will only render it if the user has added something to it.
4765
    // We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
4766
    // This fallback is particularly important as it prevents ImGui:: calls from crashing.
4767
34.4k
    g.WithinFrameScopeWithImplicitWindow = true;
4768
34.4k
    SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
4769
34.4k
    Begin("Debug##Default");
4770
34.4k
    IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
4771
4772
34.4k
    CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
4773
34.4k
}
4774
4775
// FIXME: Add a more explicit sort order in the window structure.
4776
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
4777
0
{
4778
0
    const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
4779
0
    const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
4780
0
    if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
4781
0
        return d;
4782
0
    if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
4783
0
        return d;
4784
0
    return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
4785
0
}
4786
4787
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
4788
103k
{
4789
103k
    out_sorted_windows->push_back(window);
4790
103k
    if (window->Active)
4791
37.4k
    {
4792
37.4k
        int count = window->DC.ChildWindows.Size;
4793
37.4k
        ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
4794
40.4k
        for (int i = 0; i < count; i++)
4795
3.02k
        {
4796
3.02k
            ImGuiWindow* child = window->DC.ChildWindows[i];
4797
3.02k
            if (child->Active)
4798
3.02k
                AddWindowToSortBuffer(out_sorted_windows, child);
4799
3.02k
        }
4800
37.4k
    }
4801
103k
}
4802
4803
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
4804
36.7k
{
4805
36.7k
    if (draw_list->CmdBuffer.Size == 0)
4806
0
        return;
4807
36.7k
    if (draw_list->CmdBuffer.Size == 1 && draw_list->CmdBuffer[0].ElemCount == 0 && draw_list->CmdBuffer[0].UserCallback == NULL)
4808
24
        return;
4809
4810
    // Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc.
4811
    // May trigger for you if you are using PrimXXX functions incorrectly.
4812
36.7k
    IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
4813
36.7k
    IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
4814
36.7k
    if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
4815
36.7k
        IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
4816
4817
    // Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
4818
    // If this assert triggers because you are drawing lots of stuff manually:
4819
    // - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
4820
    //   Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
4821
    // - If you want large meshes with more than 64K vertices, you can either:
4822
    //   (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
4823
    //       Most example backends already support this from 1.71. Pre-1.71 backends won't.
4824
    //       Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
4825
    //   (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
4826
    //       Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
4827
    //         glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
4828
    //       Your own engine or render API may use different parameters or function calls to specify index sizes.
4829
    //       2 and 4 bytes indices are generally supported by most graphics API.
4830
    // - If for some reason neither of those solutions works for you, a workaround is to call BeginChild()/EndChild() before reaching
4831
    //   the 64K limit to split your draw commands in multiple draw lists.
4832
36.7k
    if (sizeof(ImDrawIdx) == 2)
4833
36.7k
        IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
4834
4835
36.7k
    out_list->push_back(draw_list);
4836
36.7k
}
4837
4838
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
4839
36.7k
{
4840
36.7k
    ImGuiContext& g = *GImGui;
4841
36.7k
    ImGuiViewportP* viewport = window->Viewport;
4842
36.7k
    g.IO.MetricsRenderWindows++;
4843
36.7k
    if (window->Flags & ImGuiWindowFlags_DockNodeHost)
4844
0
        window->DrawList->ChannelsMerge();
4845
36.7k
    AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
4846
39.7k
    for (int i = 0; i < window->DC.ChildWindows.Size; i++)
4847
3.02k
    {
4848
3.02k
        ImGuiWindow* child = window->DC.ChildWindows[i];
4849
3.02k
        if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
4850
2.30k
            AddWindowToDrawData(child, layer);
4851
3.02k
    }
4852
36.7k
}
4853
4854
static inline int GetWindowDisplayLayer(ImGuiWindow* window)
4855
34.4k
{
4856
34.4k
    return (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
4857
34.4k
}
4858
4859
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
4860
static inline void AddRootWindowToDrawData(ImGuiWindow* window)
4861
34.4k
{
4862
34.4k
    AddWindowToDrawData(window, GetWindowDisplayLayer(window));
4863
34.4k
}
4864
4865
void ImDrawDataBuilder::FlattenIntoSingleLayer()
4866
34.4k
{
4867
34.4k
    int n = Layers[0].Size;
4868
34.4k
    int size = n;
4869
68.8k
    for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
4870
34.4k
        size += Layers[i].Size;
4871
34.4k
    Layers[0].resize(size);
4872
68.8k
    for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
4873
34.4k
    {
4874
34.4k
        ImVector<ImDrawList*>& layer = Layers[layer_n];
4875
34.4k
        if (layer.empty())
4876
34.4k
            continue;
4877
0
        memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
4878
0
        n += layer.Size;
4879
0
        layer.resize(0);
4880
0
    }
4881
34.4k
}
4882
4883
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
4884
34.4k
{
4885
    // When minimized, we report draw_data->DisplaySize as zero to be consistent with non-viewport mode,
4886
    // and to allow applications/backends to easily skip rendering.
4887
    // FIXME: Note that we however do NOT attempt to report "zero drawlist / vertices" into the ImDrawData structure.
4888
    // This is because the work has been done already, and its wasted! We should fix that and add optimizations for
4889
    // it earlier in the pipeline, rather than pretend to hide the data at the end of the pipeline.
4890
34.4k
    const bool is_minimized = (viewport->Flags & ImGuiViewportFlags_Minimized) != 0;
4891
4892
34.4k
    ImGuiIO& io = ImGui::GetIO();
4893
34.4k
    ImDrawData* draw_data = &viewport->DrawDataP;
4894
34.4k
    viewport->DrawData = draw_data; // Make publicly accessible
4895
34.4k
    draw_data->Valid = true;
4896
34.4k
    draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
4897
34.4k
    draw_data->CmdListsCount = draw_lists->Size;
4898
34.4k
    draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
4899
34.4k
    draw_data->DisplayPos = viewport->Pos;
4900
34.4k
    draw_data->DisplaySize = is_minimized ? ImVec2(0.0f, 0.0f) : viewport->Size;
4901
34.4k
    draw_data->FramebufferScale = io.DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
4902
34.4k
    draw_data->OwnerViewport = viewport;
4903
71.1k
    for (int n = 0; n < draw_lists->Size; n++)
4904
36.7k
    {
4905
36.7k
        ImDrawList* draw_list = draw_lists->Data[n];
4906
36.7k
        draw_list->_PopUnusedDrawCmd();
4907
36.7k
        draw_data->TotalVtxCount += draw_list->VtxBuffer.Size;
4908
36.7k
        draw_data->TotalIdxCount += draw_list->IdxBuffer.Size;
4909
36.7k
    }
4910
34.4k
}
4911
4912
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
4913
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
4914
//   so that e.g. (int)(max.x-min.x) in user's render produce correct result.
4915
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
4916
//   some frequently called functions which to modify both channels and clipping simultaneously tend to use the
4917
//   more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
4918
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
4919
143k
{
4920
143k
    ImGuiWindow* window = GetCurrentWindow();
4921
143k
    window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
4922
143k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4923
143k
}
4924
4925
void ImGui::PopClipRect()
4926
71.9k
{
4927
71.9k
    ImGuiWindow* window = GetCurrentWindow();
4928
71.9k
    window->DrawList->PopClipRect();
4929
71.9k
    window->ClipRect = window->DrawList->_ClipRectStack.back();
4930
71.9k
}
4931
4932
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
4933
0
{
4934
0
    for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
4935
0
        if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
4936
0
            return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
4937
0
    return window;
4938
0
}
4939
4940
static void ImGui::RenderDimmedBackgroundBehindWindow(ImGuiWindow* window, ImU32 col)
4941
0
{
4942
0
    if ((col & IM_COL32_A_MASK) == 0)
4943
0
        return;
4944
4945
0
    ImGuiViewportP* viewport = window->Viewport;
4946
0
    ImRect viewport_rect = viewport->GetMainRect();
4947
4948
    // Draw behind window by moving the draw command at the FRONT of the draw list
4949
0
    {
4950
        // We've already called AddWindowToDrawData() which called DrawList->ChannelsMerge() on DockNodeHost windows,
4951
        // and draw list have been trimmed already, hence the explicit recreation of a draw command if missing.
4952
        // FIXME: This is creating complication, might be simpler if we could inject a drawlist in drawdata at a given position and not attempt to manipulate ImDrawCmd order.
4953
0
        ImDrawList* draw_list = window->RootWindowDockTree->DrawList;
4954
0
        if (draw_list->CmdBuffer.Size == 0)
4955
0
            draw_list->AddDrawCmd();
4956
0
        draw_list->PushClipRect(viewport_rect.Min - ImVec2(1, 1), viewport_rect.Max + ImVec2(1, 1), false); // Ensure ImDrawCmd are not merged
4957
0
        draw_list->AddRectFilled(viewport_rect.Min, viewport_rect.Max, col);
4958
0
        ImDrawCmd cmd = draw_list->CmdBuffer.back();
4959
0
        IM_ASSERT(cmd.ElemCount == 6);
4960
0
        draw_list->CmdBuffer.pop_back();
4961
0
        draw_list->CmdBuffer.push_front(cmd);
4962
0
        draw_list->PopClipRect();
4963
0
        draw_list->AddDrawCmd(); // We need to create a command as CmdBuffer.back().IdxOffset won't be correct if we append to same command.
4964
0
    }
4965
4966
    // Draw over sibling docking nodes in a same docking tree
4967
0
    if (window->RootWindow->DockIsActive)
4968
0
    {
4969
0
        ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindowDockTree)->DrawList;
4970
0
        if (draw_list->CmdBuffer.Size == 0)
4971
0
            draw_list->AddDrawCmd();
4972
0
        draw_list->PushClipRect(viewport_rect.Min, viewport_rect.Max, false);
4973
0
        RenderRectFilledWithHole(draw_list, window->RootWindowDockTree->Rect(), window->RootWindow->Rect(), col, 0.0f);// window->RootWindowDockTree->WindowRounding);
4974
0
        draw_list->PopClipRect();
4975
0
    }
4976
0
}
4977
4978
ImGuiWindow* ImGui::FindBottomMostVisibleWindowWithinBeginStack(ImGuiWindow* parent_window)
4979
0
{
4980
0
    ImGuiContext& g = *GImGui;
4981
0
    ImGuiWindow* bottom_most_visible_window = parent_window;
4982
0
    for (int i = FindWindowDisplayIndex(parent_window); i >= 0; i--)
4983
0
    {
4984
0
        ImGuiWindow* window = g.Windows[i];
4985
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
4986
0
            continue;
4987
0
        if (!IsWindowWithinBeginStackOf(window, parent_window))
4988
0
            break;
4989
0
        if (IsWindowActiveAndVisible(window) && GetWindowDisplayLayer(window) <= GetWindowDisplayLayer(parent_window))
4990
0
            bottom_most_visible_window = window;
4991
0
    }
4992
0
    return bottom_most_visible_window;
4993
0
}
4994
4995
static void ImGui::RenderDimmedBackgrounds()
4996
34.4k
{
4997
34.4k
    ImGuiContext& g = *GImGui;
4998
34.4k
    ImGuiWindow* modal_window = GetTopMostAndVisiblePopupModal();
4999
34.4k
    if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
5000
34.4k
        return;
5001
0
    const bool dim_bg_for_modal = (modal_window != NULL);
5002
0
    const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL && g.NavWindowingTargetAnim->Active);
5003
0
    if (!dim_bg_for_modal && !dim_bg_for_window_list)
5004
0
        return;
5005
5006
0
    ImGuiViewport* viewports_already_dimmed[2] = { NULL, NULL };
5007
0
    if (dim_bg_for_modal)
5008
0
    {
5009
        // Draw dimming behind modal or a begin stack child, whichever comes first in draw order.
5010
0
        ImGuiWindow* dim_behind_window = FindBottomMostVisibleWindowWithinBeginStack(modal_window);
5011
0
        RenderDimmedBackgroundBehindWindow(dim_behind_window, GetColorU32(ImGuiCol_ModalWindowDimBg, g.DimBgRatio));
5012
0
        viewports_already_dimmed[0] = modal_window->Viewport;
5013
0
    }
5014
0
    else if (dim_bg_for_window_list)
5015
0
    {
5016
        // Draw dimming behind CTRL+Tab target window and behind CTRL+Tab UI window
5017
0
        RenderDimmedBackgroundBehindWindow(g.NavWindowingTargetAnim, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5018
0
        if (g.NavWindowingListWindow != NULL && g.NavWindowingListWindow->Viewport && g.NavWindowingListWindow->Viewport != g.NavWindowingTargetAnim->Viewport)
5019
0
            RenderDimmedBackgroundBehindWindow(g.NavWindowingListWindow, GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio));
5020
0
        viewports_already_dimmed[0] = g.NavWindowingTargetAnim->Viewport;
5021
0
        viewports_already_dimmed[1] = g.NavWindowingListWindow ? g.NavWindowingListWindow->Viewport : NULL;
5022
5023
        // Draw border around CTRL+Tab target window
5024
0
        ImGuiWindow* window = g.NavWindowingTargetAnim;
5025
0
        ImGuiViewport* viewport = window->Viewport;
5026
0
        float distance = g.FontSize;
5027
0
        ImRect bb = window->Rect();
5028
0
        bb.Expand(distance);
5029
0
        if (bb.GetWidth() >= viewport->Size.x && bb.GetHeight() >= viewport->Size.y)
5030
0
            bb.Expand(-distance - 1.0f); // If a window fits the entire viewport, adjust its highlight inward
5031
0
        if (window->DrawList->CmdBuffer.Size == 0)
5032
0
            window->DrawList->AddDrawCmd();
5033
0
        window->DrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size);
5034
0
        window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), window->WindowRounding, 0, 3.0f);
5035
0
        window->DrawList->PopClipRect();
5036
0
    }
5037
5038
    // Draw dimming background on _other_ viewports than the ones our windows are in
5039
0
    for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
5040
0
    {
5041
0
        ImGuiViewportP* viewport = g.Viewports[viewport_n];
5042
0
        if (viewport == viewports_already_dimmed[0] || viewport == viewports_already_dimmed[1])
5043
0
            continue;
5044
0
        if (modal_window && viewport->Window && IsWindowAbove(viewport->Window, modal_window))
5045
0
            continue;
5046
0
        ImDrawList* draw_list = GetForegroundDrawList(viewport);
5047
0
        const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
5048
0
        draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
5049
0
    }
5050
0
}
5051
5052
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
5053
void ImGui::EndFrame()
5054
68.8k
{
5055
68.8k
    ImGuiContext& g = *GImGui;
5056
68.8k
    IM_ASSERT(g.Initialized);
5057
5058
    // Don't process EndFrame() multiple times.
5059
68.8k
    if (g.FrameCountEnded == g.FrameCount)
5060
34.4k
        return;
5061
34.4k
    IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
5062
5063
34.4k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
5064
5065
34.4k
    ErrorCheckEndFrameSanityChecks();
5066
5067
    // Notify Platform/OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
5068
34.4k
    ImGuiPlatformImeData* ime_data = &g.PlatformImeData;
5069
34.4k
    if (g.IO.SetPlatformImeDataFn && memcmp(ime_data, &g.PlatformImeDataPrev, sizeof(ImGuiPlatformImeData)) != 0)
5070
0
    {
5071
0
        ImGuiViewport* viewport = FindViewportByID(g.PlatformImeViewport);
5072
0
        IMGUI_DEBUG_LOG_IO("Calling io.SetPlatformImeDataFn(): WantVisible: %d, InputPos (%.2f,%.2f)\n", ime_data->WantVisible, ime_data->InputPos.x, ime_data->InputPos.y);
5073
0
        g.IO.SetPlatformImeDataFn(viewport ? viewport : GetMainViewport(), ime_data);
5074
0
    }
5075
5076
    // Hide implicit/fallback "Debug" window if it hasn't been used
5077
34.4k
    g.WithinFrameScopeWithImplicitWindow = false;
5078
34.4k
    if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
5079
34.4k
        g.CurrentWindow->Active = false;
5080
34.4k
    End();
5081
5082
    // Update navigation: CTRL+Tab, wrap-around requests
5083
34.4k
    NavEndFrame();
5084
5085
    // Update docking
5086
34.4k
    DockContextEndFrame(&g);
5087
5088
34.4k
    SetCurrentViewport(NULL, NULL);
5089
5090
    // Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
5091
34.4k
    if (g.DragDropActive)
5092
119
    {
5093
119
        bool is_delivered = g.DragDropPayload.Delivery;
5094
119
        bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
5095
119
        if (is_delivered || is_elapsed)
5096
22
            ClearDragDrop();
5097
119
    }
5098
5099
    // Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
5100
34.4k
    if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
5101
0
    {
5102
0
        g.DragDropWithinSource = true;
5103
0
        SetTooltip("...");
5104
0
        g.DragDropWithinSource = false;
5105
0
    }
5106
5107
    // End frame
5108
34.4k
    g.WithinFrameScope = false;
5109
34.4k
    g.FrameCountEnded = g.FrameCount;
5110
5111
    // Initiate moving window + handle left-click and right-click focus
5112
34.4k
    UpdateMouseMovingWindowEndFrame();
5113
5114
    // Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
5115
34.4k
    UpdateViewportsEndFrame();
5116
5117
    // Sort the window list so that all child windows are after their parent
5118
    // We cannot do that on FocusWindow() because children may not exist yet
5119
34.4k
    g.WindowsTempSortBuffer.resize(0);
5120
34.4k
    g.WindowsTempSortBuffer.reserve(g.Windows.Size);
5121
137k
    for (int i = 0; i != g.Windows.Size; i++)
5122
103k
    {
5123
103k
        ImGuiWindow* window = g.Windows[i];
5124
103k
        if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow))       // if a child is active its parent will add it
5125
3.02k
            continue;
5126
100k
        AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
5127
100k
    }
5128
5129
    // This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
5130
34.4k
    IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
5131
34.4k
    g.Windows.swap(g.WindowsTempSortBuffer);
5132
34.4k
    g.IO.MetricsActiveWindows = g.WindowsActiveCount;
5133
5134
    // Unlock font atlas
5135
34.4k
    g.IO.Fonts->Locked = false;
5136
5137
    // Clear Input data for next frame
5138
34.4k
    g.IO.AppFocusLost = false;
5139
34.4k
    g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
5140
34.4k
    g.IO.InputQueueCharacters.resize(0);
5141
5142
34.4k
    CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
5143
34.4k
}
5144
5145
// Prepare the data for rendering so you can call GetDrawData()
5146
// (As with anything within the ImGui:: namspace this doesn't touch your GPU or graphics API at all:
5147
// it is the role of the ImGui_ImplXXXX_RenderDrawData() function provided by the renderer backend)
5148
void ImGui::Render()
5149
34.4k
{
5150
34.4k
    ImGuiContext& g = *GImGui;
5151
34.4k
    IM_ASSERT(g.Initialized);
5152
5153
34.4k
    if (g.FrameCountEnded != g.FrameCount)
5154
34.4k
        EndFrame();
5155
34.4k
    const bool first_render_of_frame = (g.FrameCountRendered != g.FrameCount);
5156
34.4k
    g.FrameCountRendered = g.FrameCount;
5157
34.4k
    g.IO.MetricsRenderWindows = 0;
5158
5159
34.4k
    CallContextHooks(&g, ImGuiContextHookType_RenderPre);
5160
5161
    // Add background ImDrawList (for each active viewport)
5162
68.8k
    for (int n = 0; n != g.Viewports.Size; n++)
5163
34.4k
    {
5164
34.4k
        ImGuiViewportP* viewport = g.Viewports[n];
5165
34.4k
        viewport->DrawDataBuilder.Clear();
5166
34.4k
        if (viewport->DrawLists[0] != NULL)
5167
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
5168
34.4k
    }
5169
5170
    // Add ImDrawList to render
5171
34.4k
    ImGuiWindow* windows_to_render_top_most[2];
5172
34.4k
    windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindowDockTree : NULL;
5173
34.4k
    windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
5174
137k
    for (int n = 0; n != g.Windows.Size; n++)
5175
103k
    {
5176
103k
        ImGuiWindow* window = g.Windows[n];
5177
103k
        IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
5178
103k
        if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
5179
34.4k
            AddRootWindowToDrawData(window);
5180
103k
    }
5181
103k
    for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
5182
68.8k
        if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
5183
0
            AddRootWindowToDrawData(windows_to_render_top_most[n]);
5184
5185
    // Draw modal/window whitening backgrounds
5186
34.4k
    if (first_render_of_frame)
5187
34.4k
        RenderDimmedBackgrounds();
5188
5189
    // Draw software mouse cursor if requested by io.MouseDrawCursor flag
5190
34.4k
    if (g.IO.MouseDrawCursor && first_render_of_frame && g.MouseCursor != ImGuiMouseCursor_None)
5191
0
        RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
5192
5193
    // Setup ImDrawData structures for end-user
5194
34.4k
    g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
5195
68.8k
    for (int n = 0; n < g.Viewports.Size; n++)
5196
34.4k
    {
5197
34.4k
        ImGuiViewportP* viewport = g.Viewports[n];
5198
34.4k
        viewport->DrawDataBuilder.FlattenIntoSingleLayer();
5199
5200
        // Add foreground ImDrawList (for each active viewport)
5201
34.4k
        if (viewport->DrawLists[1] != NULL)
5202
0
            AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
5203
5204
34.4k
        SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
5205
34.4k
        ImDrawData* draw_data = viewport->DrawData;
5206
34.4k
        g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
5207
34.4k
        g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
5208
34.4k
    }
5209
5210
34.4k
    CallContextHooks(&g, ImGuiContextHookType_RenderPost);
5211
34.4k
}
5212
5213
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
5214
// CalcTextSize("") should return ImVec2(0.0f, g.FontSize)
5215
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
5216
68.8k
{
5217
68.8k
    ImGuiContext& g = *GImGui;
5218
5219
68.8k
    const char* text_display_end;
5220
68.8k
    if (hide_text_after_double_hash)
5221
68.8k
        text_display_end = FindRenderedTextEnd(text, text_end);      // Hide anything after a '##' string
5222
0
    else
5223
0
        text_display_end = text_end;
5224
5225
68.8k
    ImFont* font = g.Font;
5226
68.8k
    const float font_size = g.FontSize;
5227
68.8k
    if (text == text_display_end)
5228
0
        return ImVec2(0.0f, font_size);
5229
68.8k
    ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
5230
5231
    // Round
5232
    // FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
5233
    // FIXME: Investigate using ceilf or e.g.
5234
    // - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
5235
    // - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
5236
68.8k
    text_size.x = IM_FLOOR(text_size.x + 0.99999f);
5237
5238
68.8k
    return text_size;
5239
68.8k
}
5240
5241
// Find window given position, search front-to-back
5242
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
5243
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
5244
// called, aka before the next Begin(). Moving window isn't affected.
5245
static void FindHoveredWindow()
5246
34.4k
{
5247
34.4k
    ImGuiContext& g = *GImGui;
5248
5249
    // Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
5250
34.4k
    ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
5251
34.4k
    if (g.MovingWindow)
5252
136
        g.MovingWindow->Viewport = g.MouseViewport;
5253
5254
34.4k
    ImGuiWindow* hovered_window = NULL;
5255
34.4k
    ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
5256
34.4k
    if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
5257
136
        hovered_window = g.MovingWindow;
5258
5259
34.4k
    ImVec2 padding_regular = g.Style.TouchExtraPadding;
5260
34.4k
    ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
5261
134k
    for (int i = g.Windows.Size - 1; i >= 0; i--)
5262
101k
    {
5263
101k
        ImGuiWindow* window = g.Windows[i];
5264
101k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5265
101k
        if (!window->Active || window->Hidden)
5266
65.2k
            continue;
5267
36.6k
        if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
5268
0
            continue;
5269
36.6k
        IM_ASSERT(window->Viewport);
5270
36.6k
        if (window->Viewport != g.MouseViewport)
5271
0
            continue;
5272
5273
        // Using the clipped AABB, a child window will typically be clipped by its parent (not always)
5274
36.6k
        ImRect bb(window->OuterRectClipped);
5275
36.6k
        if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
5276
2.30k
            bb.Expand(padding_regular);
5277
34.2k
        else
5278
34.2k
            bb.Expand(padding_for_resize);
5279
36.6k
        if (!bb.Contains(g.IO.MousePos))
5280
35.1k
            continue;
5281
5282
        // Support for one rectangular hole in any given window
5283
        // FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
5284
1.46k
        if (window->HitTestHoleSize.x != 0)
5285
0
        {
5286
0
            ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
5287
0
            ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
5288
0
            if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
5289
0
                continue;
5290
0
        }
5291
5292
1.46k
        if (hovered_window == NULL)
5293
1.37k
            hovered_window = window;
5294
1.46k
        IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
5295
1.46k
        if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindowDockTree != g.MovingWindow->RootWindowDockTree))
5296
1.37k
            hovered_window_ignoring_moving_window = window;
5297
1.46k
        if (hovered_window && hovered_window_ignoring_moving_window)
5298
1.37k
            break;
5299
1.46k
    }
5300
5301
34.4k
    g.HoveredWindow = hovered_window;
5302
34.4k
    g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
5303
5304
34.4k
    if (g.MovingWindow)
5305
136
        g.MovingWindow->Viewport = moving_window_viewport;
5306
34.4k
}
5307
5308
bool ImGui::IsItemActive()
5309
68.8k
{
5310
68.8k
    ImGuiContext& g = *GImGui;
5311
68.8k
    if (g.ActiveId)
5312
834
        return g.ActiveId == g.LastItemData.ID;
5313
68.0k
    return false;
5314
68.8k
}
5315
5316
bool ImGui::IsItemActivated()
5317
0
{
5318
0
    ImGuiContext& g = *GImGui;
5319
0
    if (g.ActiveId)
5320
0
        if (g.ActiveId == g.LastItemData.ID && g.ActiveIdPreviousFrame != g.LastItemData.ID)
5321
0
            return true;
5322
0
    return false;
5323
0
}
5324
5325
bool ImGui::IsItemDeactivated()
5326
0
{
5327
0
    ImGuiContext& g = *GImGui;
5328
0
    if (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDeactivated)
5329
0
        return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
5330
0
    return (g.ActiveIdPreviousFrame == g.LastItemData.ID && g.ActiveIdPreviousFrame != 0 && g.ActiveId != g.LastItemData.ID);
5331
0
}
5332
5333
bool ImGui::IsItemDeactivatedAfterEdit()
5334
0
{
5335
0
    ImGuiContext& g = *GImGui;
5336
0
    return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
5337
0
}
5338
5339
// == GetItemID() == GetFocusID()
5340
bool ImGui::IsItemFocused()
5341
0
{
5342
0
    ImGuiContext& g = *GImGui;
5343
0
    if (g.NavId != g.LastItemData.ID || g.NavId == 0)
5344
0
        return false;
5345
5346
    // Special handling for the dummy item after Begin() which represent the title bar or tab.
5347
    // When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
5348
0
    ImGuiWindow* window = g.CurrentWindow;
5349
0
    if (g.LastItemData.ID == window->ID && window->WriteAccessed)
5350
0
        return false;
5351
5352
0
    return true;
5353
0
}
5354
5355
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
5356
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
5357
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
5358
0
{
5359
0
    return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
5360
0
}
5361
5362
bool ImGui::IsItemToggledOpen()
5363
0
{
5364
0
    ImGuiContext& g = *GImGui;
5365
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
5366
0
}
5367
5368
bool ImGui::IsItemToggledSelection()
5369
0
{
5370
0
    ImGuiContext& g = *GImGui;
5371
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
5372
0
}
5373
5374
bool ImGui::IsAnyItemHovered()
5375
0
{
5376
0
    ImGuiContext& g = *GImGui;
5377
0
    return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
5378
0
}
5379
5380
bool ImGui::IsAnyItemActive()
5381
0
{
5382
0
    ImGuiContext& g = *GImGui;
5383
0
    return g.ActiveId != 0;
5384
0
}
5385
5386
bool ImGui::IsAnyItemFocused()
5387
0
{
5388
0
    ImGuiContext& g = *GImGui;
5389
0
    return g.NavId != 0 && !g.NavDisableHighlight;
5390
0
}
5391
5392
bool ImGui::IsItemVisible()
5393
0
{
5394
0
    ImGuiContext& g = *GImGui;
5395
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Visible) != 0;
5396
0
}
5397
5398
bool ImGui::IsItemEdited()
5399
0
{
5400
0
    ImGuiContext& g = *GImGui;
5401
0
    return (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_Edited) != 0;
5402
0
}
5403
5404
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
5405
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
5406
void ImGui::SetItemAllowOverlap()
5407
0
{
5408
0
    ImGuiContext& g = *GImGui;
5409
0
    ImGuiID id = g.LastItemData.ID;
5410
0
    if (g.HoveredId == id)
5411
0
        g.HoveredIdAllowOverlap = true;
5412
0
    if (g.ActiveId == id)
5413
0
        g.ActiveIdAllowOverlap = true;
5414
0
}
5415
5416
// FIXME: It might be undesirable that this will likely disable KeyOwner-aware shortcuts systems. Consider a more fine-tuned version for the two users of this function.
5417
void ImGui::SetActiveIdUsingAllKeyboardKeys()
5418
133
{
5419
133
    ImGuiContext& g = *GImGui;
5420
133
    IM_ASSERT(g.ActiveId != 0);
5421
133
    g.ActiveIdUsingNavDirMask = (1 << ImGuiDir_COUNT) - 1;
5422
133
    g.ActiveIdUsingAllKeyboardKeys = true;
5423
133
    NavMoveRequestCancel();
5424
133
}
5425
5426
ImGuiID ImGui::GetItemID()
5427
0
{
5428
0
    ImGuiContext& g = *GImGui;
5429
0
    return g.LastItemData.ID;
5430
0
}
5431
5432
ImVec2 ImGui::GetItemRectMin()
5433
0
{
5434
0
    ImGuiContext& g = *GImGui;
5435
0
    return g.LastItemData.Rect.Min;
5436
0
}
5437
5438
ImVec2 ImGui::GetItemRectMax()
5439
0
{
5440
0
    ImGuiContext& g = *GImGui;
5441
0
    return g.LastItemData.Rect.Max;
5442
0
}
5443
5444
ImVec2 ImGui::GetItemRectSize()
5445
0
{
5446
0
    ImGuiContext& g = *GImGui;
5447
0
    return g.LastItemData.Rect.GetSize();
5448
0
}
5449
5450
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
5451
3.02k
{
5452
3.02k
    ImGuiContext& g = *GImGui;
5453
3.02k
    ImGuiWindow* parent_window = g.CurrentWindow;
5454
5455
3.02k
    flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoDocking;
5456
3.02k
    flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove);  // Inherit the NoMove flag
5457
5458
    // Size
5459
3.02k
    const ImVec2 content_avail = GetContentRegionAvail();
5460
3.02k
    ImVec2 size = ImFloor(size_arg);
5461
3.02k
    const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
5462
3.02k
    if (size.x <= 0.0f)
5463
2.77k
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too many issues)
5464
3.02k
    if (size.y <= 0.0f)
5465
2.52k
        size.y = ImMax(content_avail.y + size.y, 4.0f);
5466
3.02k
    SetNextWindowSize(size);
5467
5468
    // Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
5469
3.02k
    const char* temp_window_name;
5470
3.02k
    if (name)
5471
3.02k
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%s_%08X", parent_window->Name, name, id);
5472
0
    else
5473
0
        ImFormatStringToTempBuffer(&temp_window_name, NULL, "%s/%08X", parent_window->Name, id);
5474
5475
3.02k
    const float backup_border_size = g.Style.ChildBorderSize;
5476
3.02k
    if (!border)
5477
1.77k
        g.Style.ChildBorderSize = 0.0f;
5478
3.02k
    bool ret = Begin(temp_window_name, NULL, flags);
5479
3.02k
    g.Style.ChildBorderSize = backup_border_size;
5480
5481
3.02k
    ImGuiWindow* child_window = g.CurrentWindow;
5482
3.02k
    child_window->ChildId = id;
5483
3.02k
    child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
5484
5485
    // Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
5486
    // While this is not really documented/defined, it seems that the expected thing to do.
5487
3.02k
    if (child_window->BeginCount == 1)
5488
3.02k
        parent_window->DC.CursorPos = child_window->Pos;
5489
5490
    // Process navigation-in immediately so NavInit can run on first frame
5491
3.02k
    if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
5492
0
    {
5493
0
        FocusWindow(child_window);
5494
0
        NavInitWindow(child_window, false);
5495
0
        SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary id so that key-press won't activate child item
5496
0
        g.ActiveIdSource = ImGuiInputSource_Nav;
5497
0
    }
5498
3.02k
    return ret;
5499
3.02k
}
5500
5501
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5502
3.02k
{
5503
3.02k
    ImGuiWindow* window = GetCurrentWindow();
5504
3.02k
    return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
5505
3.02k
}
5506
5507
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
5508
0
{
5509
0
    IM_ASSERT(id != 0);
5510
0
    return BeginChildEx(NULL, id, size_arg, border, extra_flags);
5511
0
}
5512
5513
void ImGui::EndChild()
5514
3.02k
{
5515
3.02k
    ImGuiContext& g = *GImGui;
5516
3.02k
    ImGuiWindow* window = g.CurrentWindow;
5517
5518
3.02k
    IM_ASSERT(g.WithinEndChild == false);
5519
3.02k
    IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow);   // Mismatched BeginChild()/EndChild() calls
5520
5521
3.02k
    g.WithinEndChild = true;
5522
3.02k
    if (window->BeginCount > 1)
5523
0
    {
5524
0
        End();
5525
0
    }
5526
3.02k
    else
5527
3.02k
    {
5528
3.02k
        ImVec2 sz = window->Size;
5529
3.02k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
5530
2.77k
            sz.x = ImMax(4.0f, sz.x);
5531
3.02k
        if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
5532
2.52k
            sz.y = ImMax(4.0f, sz.y);
5533
3.02k
        End();
5534
5535
3.02k
        ImGuiWindow* parent_window = g.CurrentWindow;
5536
3.02k
        ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
5537
3.02k
        ItemSize(sz);
5538
3.02k
        if ((window->DC.NavLayersActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
5539
1.69k
        {
5540
1.69k
            ItemAdd(bb, window->ChildId);
5541
1.69k
            RenderNavHighlight(bb, window->ChildId);
5542
5543
            // When browsing a window that has no activable items (scroll only) we keep a highlight on the child (pass g.NavId to trick into always displaying)
5544
1.69k
            if (window->DC.NavLayersActiveMask == 0 && window == g.NavWindow)
5545
1.01k
                RenderNavHighlight(ImRect(bb.Min - ImVec2(2, 2), bb.Max + ImVec2(2, 2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
5546
1.69k
        }
5547
1.32k
        else
5548
1.32k
        {
5549
            // Not navigable into
5550
1.32k
            ItemAdd(bb, 0);
5551
1.32k
        }
5552
3.02k
        if (g.HoveredWindow == window)
5553
142
            g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
5554
3.02k
    }
5555
3.02k
    g.WithinEndChild = false;
5556
3.02k
    g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
5557
3.02k
}
5558
5559
// Helper to create a child window / scrolling region that looks like a normal widget frame.
5560
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
5561
0
{
5562
0
    ImGuiContext& g = *GImGui;
5563
0
    const ImGuiStyle& style = g.Style;
5564
0
    PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
5565
0
    PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
5566
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
5567
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
5568
0
    bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
5569
0
    PopStyleVar(3);
5570
0
    PopStyleColor();
5571
0
    return ret;
5572
0
}
5573
5574
void ImGui::EndChildFrame()
5575
0
{
5576
0
    EndChild();
5577
0
}
5578
5579
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
5580
38
{
5581
38
    window->SetWindowPosAllowFlags       = enabled ? (window->SetWindowPosAllowFlags       | flags) : (window->SetWindowPosAllowFlags       & ~flags);
5582
38
    window->SetWindowSizeAllowFlags      = enabled ? (window->SetWindowSizeAllowFlags      | flags) : (window->SetWindowSizeAllowFlags      & ~flags);
5583
38
    window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
5584
38
    window->SetWindowDockAllowFlags      = enabled ? (window->SetWindowDockAllowFlags      | flags) : (window->SetWindowDockAllowFlags      & ~flags);
5585
38
}
5586
5587
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
5588
71.9k
{
5589
71.9k
    ImGuiContext& g = *GImGui;
5590
71.9k
    return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
5591
71.9k
}
5592
5593
ImGuiWindow* ImGui::FindWindowByName(const char* name)
5594
71.9k
{
5595
71.9k
    ImGuiID id = ImHashStr(name);
5596
71.9k
    return FindWindowByID(id);
5597
71.9k
}
5598
5599
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5600
0
{
5601
0
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5602
0
    window->ViewportPos = main_viewport->Pos;
5603
0
    if (settings->ViewportId)
5604
0
    {
5605
0
        window->ViewportId = settings->ViewportId;
5606
0
        window->ViewportPos = ImVec2(settings->ViewportPos.x, settings->ViewportPos.y);
5607
0
    }
5608
0
    window->Pos = ImFloor(ImVec2(settings->Pos.x + window->ViewportPos.x, settings->Pos.y + window->ViewportPos.y));
5609
0
    if (settings->Size.x > 0 && settings->Size.y > 0)
5610
0
        window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
5611
0
    window->Collapsed = settings->Collapsed;
5612
0
    window->DockId = settings->DockId;
5613
0
    window->DockOrder = settings->DockOrder;
5614
0
}
5615
5616
static void UpdateWindowInFocusOrderList(ImGuiWindow* window, bool just_created, ImGuiWindowFlags new_flags)
5617
71.9k
{
5618
71.9k
    ImGuiContext& g = *GImGui;
5619
5620
71.9k
    const bool new_is_explicit_child = (new_flags & ImGuiWindowFlags_ChildWindow) != 0 && ((new_flags & ImGuiWindowFlags_Popup) == 0 || (new_flags & ImGuiWindowFlags_ChildMenu) != 0);
5621
71.9k
    const bool child_flag_changed = new_is_explicit_child != window->IsExplicitChild;
5622
71.9k
    if ((just_created || child_flag_changed) && !new_is_explicit_child)
5623
2
    {
5624
2
        IM_ASSERT(!g.WindowsFocusOrder.contains(window));
5625
2
        g.WindowsFocusOrder.push_back(window);
5626
2
        window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
5627
2
    }
5628
71.9k
    else if (!just_created && child_flag_changed && new_is_explicit_child)
5629
0
    {
5630
0
        IM_ASSERT(g.WindowsFocusOrder[window->FocusOrder] == window);
5631
0
        for (int n = window->FocusOrder + 1; n < g.WindowsFocusOrder.Size; n++)
5632
0
            g.WindowsFocusOrder[n]->FocusOrder--;
5633
0
        g.WindowsFocusOrder.erase(g.WindowsFocusOrder.Data + window->FocusOrder);
5634
0
        window->FocusOrder = -1;
5635
0
    }
5636
71.9k
    window->IsExplicitChild = new_is_explicit_child;
5637
71.9k
}
5638
5639
static void InitOrLoadWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
5640
3
{
5641
    // Initial window state with e.g. default/arbitrary window position
5642
    // Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
5643
3
    const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
5644
3
    window->Pos = main_viewport->Pos + ImVec2(60, 60);
5645
3
    window->ViewportPos = main_viewport->Pos;
5646
3
    window->SetWindowPosAllowFlags = window->SetWindowSizeAllowFlags = window->SetWindowCollapsedAllowFlags = window->SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
5647
5648
3
    if (settings != NULL)
5649
0
    {
5650
0
        SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
5651
0
        ApplyWindowSettings(window, settings);
5652
0
    }
5653
3
    window->DC.CursorStartPos = window->DC.CursorMaxPos = window->DC.IdealMaxPos = window->Pos; // So first call to CalcWindowContentSizes() doesn't return crazy values
5654
5655
3
    if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
5656
0
    {
5657
0
        window->AutoFitFramesX = window->AutoFitFramesY = 2;
5658
0
        window->AutoFitOnlyGrows = false;
5659
0
    }
5660
3
    else
5661
3
    {
5662
3
        if (window->Size.x <= 0.0f)
5663
3
            window->AutoFitFramesX = 2;
5664
3
        if (window->Size.y <= 0.0f)
5665
3
            window->AutoFitFramesY = 2;
5666
3
        window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
5667
3
    }
5668
3
}
5669
5670
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
5671
3
{
5672
    // Create window the first time
5673
    //IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
5674
3
    ImGuiContext& g = *GImGui;
5675
3
    ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
5676
3
    window->Flags = flags;
5677
3
    g.WindowsById.SetVoidPtr(window->ID, window);
5678
5679
3
    ImGuiWindowSettings* settings = NULL;
5680
3
    if (!(flags & ImGuiWindowFlags_NoSavedSettings))
5681
2
        if ((settings = ImGui::FindWindowSettingsByWindow(window)) != 0)
5682
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
5683
5684
3
    InitOrLoadWindowSettings(window, settings);
5685
5686
3
    if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
5687
0
        g.Windows.push_front(window); // Quite slow but rare and only once
5688
3
    else
5689
3
        g.Windows.push_back(window);
5690
5691
3
    return window;
5692
3
}
5693
5694
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
5695
0
{
5696
0
    return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
5697
0
}
5698
5699
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
5700
137k
{
5701
137k
    return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
5702
137k
}
5703
5704
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
5705
144k
{
5706
144k
    ImGuiContext& g = *GImGui;
5707
144k
    ImVec2 new_size = size_desired;
5708
144k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
5709
0
    {
5710
        // Using -1,-1 on either X/Y axis to preserve the current size.
5711
0
        ImRect cr = g.NextWindowData.SizeConstraintRect;
5712
0
        new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
5713
0
        new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
5714
0
        if (g.NextWindowData.SizeCallback)
5715
0
        {
5716
0
            ImGuiSizeCallbackData data;
5717
0
            data.UserData = g.NextWindowData.SizeCallbackUserData;
5718
0
            data.Pos = window->Pos;
5719
0
            data.CurrentSize = window->SizeFull;
5720
0
            data.DesiredSize = new_size;
5721
0
            g.NextWindowData.SizeCallback(&data);
5722
0
            new_size = data.DesiredSize;
5723
0
        }
5724
0
        new_size.x = IM_FLOOR(new_size.x);
5725
0
        new_size.y = IM_FLOOR(new_size.y);
5726
0
    }
5727
5728
    // Minimum size
5729
144k
    if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
5730
137k
    {
5731
137k
        ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
5732
137k
        new_size = ImMax(new_size, g.Style.WindowMinSize);
5733
137k
        const float minimum_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f);
5734
137k
        new_size.y = ImMax(new_size.y, minimum_height); // Reduce artifacts with very small windows
5735
137k
    }
5736
144k
    return new_size;
5737
144k
}
5738
5739
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
5740
71.9k
{
5741
71.9k
    bool preserve_old_content_sizes = false;
5742
71.9k
    if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
5743
31.4k
        preserve_old_content_sizes = true;
5744
40.5k
    else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
5745
716
        preserve_old_content_sizes = true;
5746
71.9k
    if (preserve_old_content_sizes)
5747
32.1k
    {
5748
32.1k
        *content_size_current = window->ContentSize;
5749
32.1k
        *content_size_ideal = window->ContentSizeIdeal;
5750
32.1k
        return;
5751
32.1k
    }
5752
5753
39.7k
    content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
5754
39.7k
    content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
5755
39.7k
    content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
5756
39.7k
    content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
5757
39.7k
}
5758
5759
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
5760
71.9k
{
5761
71.9k
    ImGuiContext& g = *GImGui;
5762
71.9k
    ImGuiStyle& style = g.Style;
5763
71.9k
    const float decoration_w_without_scrollbars = window->DecoOuterSizeX1 + window->DecoOuterSizeX2 - window->ScrollbarSizes.x;
5764
71.9k
    const float decoration_h_without_scrollbars = window->DecoOuterSizeY1 + window->DecoOuterSizeY2 - window->ScrollbarSizes.y;
5765
71.9k
    ImVec2 size_pad = window->WindowPadding * 2.0f;
5766
71.9k
    ImVec2 size_desired = size_contents + size_pad + ImVec2(decoration_w_without_scrollbars, decoration_h_without_scrollbars);
5767
71.9k
    if (window->Flags & ImGuiWindowFlags_Tooltip)
5768
0
    {
5769
        // Tooltip always resize
5770
0
        return size_desired;
5771
0
    }
5772
71.9k
    else
5773
71.9k
    {
5774
        // Maximum window size is determined by the viewport size or monitor size
5775
71.9k
        const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
5776
71.9k
        const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
5777
71.9k
        ImVec2 size_min = style.WindowMinSize;
5778
71.9k
        if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
5779
0
            size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
5780
5781
71.9k
        ImVec2 avail_size = window->Viewport->WorkSize;
5782
71.9k
        if (window->ViewportOwned)
5783
0
            avail_size = ImVec2(FLT_MAX, FLT_MAX);
5784
71.9k
        const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
5785
71.9k
        if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
5786
0
            avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
5787
71.9k
        ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
5788
5789
        // When the window cannot fit all contents (either because of constraints, either because screen is too small),
5790
        // we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
5791
71.9k
        ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5792
71.9k
        bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - decoration_w_without_scrollbars < size_contents.x  && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
5793
71.9k
        bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_h_without_scrollbars < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
5794
71.9k
        if (will_have_scrollbar_x)
5795
3.02k
            size_auto_fit.y += style.ScrollbarSize;
5796
71.9k
        if (will_have_scrollbar_y)
5797
31
            size_auto_fit.x += style.ScrollbarSize;
5798
71.9k
        return size_auto_fit;
5799
71.9k
    }
5800
71.9k
}
5801
5802
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
5803
0
{
5804
0
    ImVec2 size_contents_current;
5805
0
    ImVec2 size_contents_ideal;
5806
0
    CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
5807
0
    ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
5808
0
    ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5809
0
    return size_final;
5810
0
}
5811
5812
static ImGuiCol GetWindowBgColorIdx(ImGuiWindow* window)
5813
40.4k
{
5814
40.4k
    if (window->Flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
5815
0
        return ImGuiCol_PopupBg;
5816
40.4k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !window->DockIsActive)
5817
3.02k
        return ImGuiCol_ChildBg;
5818
37.4k
    return ImGuiCol_WindowBg;
5819
40.4k
}
5820
5821
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
5822
194
{
5823
194
    ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm);                // Expected window upper-left
5824
194
    ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
5825
194
    ImVec2 size_expected = pos_max - pos_min;
5826
194
    ImVec2 size_constrained = CalcWindowSizeAfterConstraint(window, size_expected);
5827
194
    *out_pos = pos_min;
5828
194
    if (corner_norm.x == 0.0f)
5829
0
        out_pos->x -= (size_constrained.x - size_expected.x);
5830
194
    if (corner_norm.y == 0.0f)
5831
0
        out_pos->y -= (size_constrained.y - size_expected.y);
5832
194
    *out_size = size_constrained;
5833
194
}
5834
5835
// Data for resizing from corner
5836
struct ImGuiResizeGripDef
5837
{
5838
    ImVec2  CornerPosN;
5839
    ImVec2  InnerDir;
5840
    int     AngleMin12, AngleMax12;
5841
};
5842
static const ImGuiResizeGripDef resize_grip_def[4] =
5843
{
5844
    { ImVec2(1, 1), ImVec2(-1, -1), 0, 3 },  // Lower-right
5845
    { ImVec2(0, 1), ImVec2(+1, -1), 3, 6 },  // Lower-left
5846
    { ImVec2(0, 0), ImVec2(+1, +1), 6, 9 },  // Upper-left (Unused)
5847
    { ImVec2(1, 0), ImVec2(-1, +1), 9, 12 }  // Upper-right (Unused)
5848
};
5849
5850
// Data for resizing from borders
5851
struct ImGuiResizeBorderDef
5852
{
5853
    ImVec2 InnerDir;
5854
    ImVec2 SegmentN1, SegmentN2;
5855
    float  OuterAngle;
5856
};
5857
static const ImGuiResizeBorderDef resize_border_def[4] =
5858
{
5859
    { ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
5860
    { ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
5861
    { ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
5862
    { ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f }  // Down
5863
};
5864
5865
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
5866
0
{
5867
0
    ImRect rect = window->Rect();
5868
0
    if (thickness == 0.0f)
5869
0
        rect.Max -= ImVec2(1, 1);
5870
0
    if (border_n == ImGuiDir_Left)  { return ImRect(rect.Min.x - thickness,    rect.Min.y + perp_padding, rect.Min.x + thickness,    rect.Max.y - perp_padding); }
5871
0
    if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness,    rect.Min.y + perp_padding, rect.Max.x + thickness,    rect.Max.y - perp_padding); }
5872
0
    if (border_n == ImGuiDir_Up)    { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness,    rect.Max.x - perp_padding, rect.Min.y + thickness);    }
5873
0
    if (border_n == ImGuiDir_Down)  { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness,    rect.Max.x - perp_padding, rect.Max.y + thickness);    }
5874
0
    IM_ASSERT(0);
5875
0
    return ImRect();
5876
0
}
5877
5878
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
5879
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
5880
0
{
5881
0
    IM_ASSERT(n >= 0 && n < 4);
5882
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5883
0
    id = ImHashStr("#RESIZE", 0, id);
5884
0
    id = ImHashData(&n, sizeof(int), id);
5885
0
    return id;
5886
0
}
5887
5888
// Borders (Left, Right, Up, Down)
5889
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
5890
0
{
5891
0
    IM_ASSERT(dir >= 0 && dir < 4);
5892
0
    int n = (int)dir + 4;
5893
0
    ImGuiID id = window->DockIsActive ? window->DockNode->HostWindow->ID : window->ID;
5894
0
    id = ImHashStr("#RESIZE", 0, id);
5895
0
    id = ImHashData(&n, sizeof(int), id);
5896
0
    return id;
5897
0
}
5898
5899
// Handle resize for: Resize Grips, Borders, Gamepad
5900
// Return true when using auto-fit (double-click on resize grip)
5901
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
5902
40.4k
{
5903
40.4k
    ImGuiContext& g = *GImGui;
5904
40.4k
    ImGuiWindowFlags flags = window->Flags;
5905
5906
40.4k
    if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
5907
3.02k
        return false;
5908
37.4k
    if (window->WasActive == false) // Early out to avoid running this code for e.g. a hidden implicit/fallback Debug window.
5909
34.4k
        return false;
5910
5911
3.02k
    bool ret_auto_fit = false;
5912
3.02k
    const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
5913
3.02k
    const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
5914
3.02k
    const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
5915
3.02k
    const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
5916
5917
3.02k
    ImVec2 pos_target(FLT_MAX, FLT_MAX);
5918
3.02k
    ImVec2 size_target(FLT_MAX, FLT_MAX);
5919
5920
    // Clip mouse interaction rectangles within the viewport rectangle (in practice the narrowing is going to happen most of the time).
5921
    // - Not narrowing would mostly benefit the situation where OS windows _without_ decoration have a threshold for hovering when outside their limits.
5922
    //   This is however not the case with current backends under Win32, but a custom borderless window implementation would benefit from it.
5923
    // - When decoration are enabled we typically benefit from that distance, but then our resize elements would be conflicting with OS resize elements, so we also narrow.
5924
    // - Note that we are unable to tell if the platform setup allows hovering with a distance threshold (on Win32, decorated window have such threshold).
5925
    // We only clip interaction so we overwrite window->ClipRect, cannot call PushClipRect() yet as DrawList is not yet setup.
5926
3.02k
    const bool clip_with_viewport_rect = !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport) || (g.IO.MouseHoveredViewport != window->ViewportId) || !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration);
5927
3.02k
    if (clip_with_viewport_rect)
5928
3.02k
        window->ClipRect = window->Viewport->GetMainRect();
5929
5930
    // Resize grips and borders are on layer 1
5931
3.02k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
5932
5933
    // Manual resize grips
5934
3.02k
    PushID("#RESIZE");
5935
6.04k
    for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
5936
3.02k
    {
5937
3.02k
        const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
5938
3.02k
        const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
5939
5940
        // Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
5941
3.02k
        bool hovered, held;
5942
3.02k
        ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
5943
3.02k
        if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
5944
3.02k
        if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
5945
3.02k
        ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
5946
3.02k
        ItemAdd(resize_rect, resize_grip_id, NULL, ImGuiItemFlags_NoNav);
5947
3.02k
        ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5948
        //GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
5949
3.02k
        if (hovered || held)
5950
246
            g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
5951
5952
3.02k
        if (held && g.IO.MouseClickedCount[0] == 2 && resize_grip_n == 0)
5953
7
        {
5954
            // Manual auto-fit when double-clicking
5955
7
            size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
5956
7
            ret_auto_fit = true;
5957
7
            ClearActiveID();
5958
7
        }
5959
3.01k
        else if (held)
5960
194
        {
5961
            // Resize from any of the four corners
5962
            // We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
5963
194
            ImVec2 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
5964
194
            ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
5965
194
            ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
5966
194
            corner_target = ImClamp(corner_target, clamp_min, clamp_max);
5967
194
            CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
5968
194
        }
5969
5970
        // Only lower-left grip is visible before hovering/activating
5971
3.02k
        if (resize_grip_n == 0 || held || hovered)
5972
3.02k
            resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
5973
3.02k
    }
5974
3.02k
    for (int border_n = 0; border_n < resize_border_count; border_n++)
5975
0
    {
5976
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_n];
5977
0
        const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
5978
5979
0
        bool hovered, held;
5980
0
        ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
5981
0
        ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
5982
0
        ItemAdd(border_rect, border_id, NULL, ImGuiItemFlags_NoNav);
5983
0
        ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
5984
        //GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
5985
0
        if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
5986
0
        {
5987
0
            g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
5988
0
            if (held)
5989
0
                *border_held = border_n;
5990
0
        }
5991
0
        if (held)
5992
0
        {
5993
0
            ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
5994
0
            ImVec2 clamp_max(border_n == ImGuiDir_Left  ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up   ? visibility_rect.Max.y : +FLT_MAX);
5995
0
            ImVec2 border_target = window->Pos;
5996
0
            border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
5997
0
            border_target = ImClamp(border_target, clamp_min, clamp_max);
5998
0
            CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
5999
0
        }
6000
0
    }
6001
3.02k
    PopID();
6002
6003
    // Restore nav layer
6004
3.02k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6005
6006
    // Navigation resize (keyboard/gamepad)
6007
    // FIXME: This cannot be moved to NavUpdateWindowing() because CalcWindowSizeAfterConstraint() need to callback into user.
6008
    // Not even sure the callback works here.
6009
3.02k
    if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindowDockTree == window)
6010
0
    {
6011
0
        ImVec2 nav_resize_dir;
6012
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
6013
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
6014
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
6015
0
            nav_resize_dir = GetKeyMagnitude2d(ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown);
6016
0
        if (nav_resize_dir.x != 0.0f || nav_resize_dir.y != 0.0f)
6017
0
        {
6018
0
            const float NAV_RESIZE_SPEED = 600.0f;
6019
0
            const float resize_step = NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y);
6020
0
            g.NavWindowingAccumDeltaSize += nav_resize_dir * resize_step;
6021
0
            g.NavWindowingAccumDeltaSize = ImMax(g.NavWindowingAccumDeltaSize, visibility_rect.Min - window->Pos - window->Size); // We need Pos+Size >= visibility_rect.Min, so Size >= visibility_rect.Min - Pos, so size_delta >= visibility_rect.Min - window->Pos - window->Size
6022
0
            g.NavWindowingToggleLayer = false;
6023
0
            g.NavDisableMouseHover = true;
6024
0
            resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
6025
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaSize);
6026
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
6027
0
            {
6028
                // FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
6029
0
                size_target = CalcWindowSizeAfterConstraint(window, window->SizeFull + accum_floored);
6030
0
                g.NavWindowingAccumDeltaSize -= accum_floored;
6031
0
            }
6032
0
        }
6033
0
    }
6034
6035
    // Apply back modified position/size to window
6036
3.02k
    if (size_target.x != FLT_MAX)
6037
201
    {
6038
201
        window->SizeFull = size_target;
6039
201
        MarkIniSettingsDirty(window);
6040
201
    }
6041
3.02k
    if (pos_target.x != FLT_MAX)
6042
194
    {
6043
194
        window->Pos = ImFloor(pos_target);
6044
194
        MarkIniSettingsDirty(window);
6045
194
    }
6046
6047
3.02k
    window->Size = window->SizeFull;
6048
3.02k
    return ret_auto_fit;
6049
37.4k
}
6050
6051
static inline void ClampWindowPos(ImGuiWindow* window, const ImRect& visibility_rect)
6052
68.8k
{
6053
68.8k
    ImGuiContext& g = *GImGui;
6054
68.8k
    ImVec2 size_for_clamping = window->Size;
6055
68.8k
    if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(window->Flags & ImGuiWindowFlags_NoTitleBar) || window->DockNodeAsHost))
6056
0
        size_for_clamping.y = ImGui::GetFrameHeight(); // Not using window->TitleBarHeight() as DockNodeAsHost will report 0.0f here.
6057
68.8k
    window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
6058
68.8k
}
6059
6060
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
6061
40.4k
{
6062
40.4k
    ImGuiContext& g = *GImGui;
6063
40.4k
    float rounding = window->WindowRounding;
6064
40.4k
    float border_size = window->WindowBorderSize;
6065
40.4k
    if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
6066
38.7k
        window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
6067
6068
40.4k
    int border_held = window->ResizeBorderHeld;
6069
40.4k
    if (border_held != -1)
6070
0
    {
6071
0
        const ImGuiResizeBorderDef& def = resize_border_def[border_held];
6072
0
        ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
6073
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
6074
0
        window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
6075
0
        window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
6076
0
    }
6077
40.4k
    if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6078
0
    {
6079
0
        float y = window->Pos.y + window->TitleBarHeight() - 1;
6080
0
        window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
6081
0
    }
6082
40.4k
}
6083
6084
// Draw background and borders
6085
// Draw and handle scrollbars
6086
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, bool handle_borders_and_resize_grips, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
6087
71.9k
{
6088
71.9k
    ImGuiContext& g = *GImGui;
6089
71.9k
    ImGuiStyle& style = g.Style;
6090
71.9k
    ImGuiWindowFlags flags = window->Flags;
6091
6092
    // Ensure that ScrollBar doesn't read last frame's SkipItems
6093
71.9k
    IM_ASSERT(window->BeginCount == 0);
6094
71.9k
    window->SkipItems = false;
6095
6096
    // Draw window + handle manual resize
6097
    // As we highlight the title bar when want_focus is set, multiple reappearing windows will have their title bar highlighted on their reappearing frame.
6098
71.9k
    const float window_rounding = window->WindowRounding;
6099
71.9k
    const float window_border_size = window->WindowBorderSize;
6100
71.9k
    if (window->Collapsed)
6101
31.4k
    {
6102
        // Title bar only
6103
31.4k
        const float backup_border_size = style.FrameBorderSize;
6104
31.4k
        g.Style.FrameBorderSize = window->WindowBorderSize;
6105
31.4k
        ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
6106
31.4k
        if (window->ViewportOwned)
6107
0
            title_bar_col |= IM_COL32_A_MASK; // No alpha (we don't support is_docking_transparent_payload here because simpler and less meaningful, but could with a bit of code shuffle/reuse)
6108
31.4k
        RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
6109
31.4k
        g.Style.FrameBorderSize = backup_border_size;
6110
31.4k
    }
6111
40.4k
    else
6112
40.4k
    {
6113
        // Window background
6114
40.4k
        if (!(flags & ImGuiWindowFlags_NoBackground))
6115
40.4k
        {
6116
40.4k
            bool is_docking_transparent_payload = false;
6117
40.4k
            if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
6118
0
                if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
6119
0
                    is_docking_transparent_payload = true;
6120
6121
40.4k
            ImU32 bg_col = GetColorU32(GetWindowBgColorIdx(window));
6122
40.4k
            if (window->ViewportOwned)
6123
0
            {
6124
0
                bg_col |= IM_COL32_A_MASK; // No alpha
6125
0
                if (is_docking_transparent_payload)
6126
0
                    window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
6127
0
            }
6128
40.4k
            else
6129
40.4k
            {
6130
                // Adjust alpha. For docking
6131
40.4k
                bool override_alpha = false;
6132
40.4k
                float alpha = 1.0f;
6133
40.4k
                if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
6134
0
                {
6135
0
                    alpha = g.NextWindowData.BgAlphaVal;
6136
0
                    override_alpha = true;
6137
0
                }
6138
40.4k
                if (is_docking_transparent_payload)
6139
0
                {
6140
0
                    alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA; // FIXME-DOCK: Should that be an override?
6141
0
                    override_alpha = true;
6142
0
                }
6143
40.4k
                if (override_alpha)
6144
0
                    bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
6145
40.4k
            }
6146
6147
            // Render, for docked windows and host windows we ensure bg goes before decorations
6148
40.4k
            if (window->DockIsActive)
6149
0
                window->DockNode->LastBgColor = bg_col;
6150
40.4k
            ImDrawList* bg_draw_list = window->DockIsActive ? window->DockNode->HostWindow->DrawList : window->DrawList;
6151
40.4k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6152
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
6153
40.4k
            bg_draw_list->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
6154
40.4k
            if (window->DockIsActive || (flags & ImGuiWindowFlags_DockNodeHost))
6155
0
                bg_draw_list->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
6156
40.4k
        }
6157
40.4k
        if (window->DockIsActive)
6158
0
            window->DockNode->IsBgDrawnThisFrame = true;
6159
6160
        // Title bar
6161
        // (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
6162
        // in order for their pos/size to be matching their undocking state.)
6163
40.4k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
6164
37.4k
        {
6165
37.4k
            ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
6166
37.4k
            window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
6167
37.4k
        }
6168
6169
        // Menu bar
6170
40.4k
        if (flags & ImGuiWindowFlags_MenuBar)
6171
0
        {
6172
0
            ImRect menu_bar_rect = window->MenuBarRect();
6173
0
            menu_bar_rect.ClipWith(window->Rect());  // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
6174
0
            window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
6175
0
            if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
6176
0
                window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
6177
0
        }
6178
6179
        // Docking: Unhide tab bar (small triangle in the corner), drag from small triangle to quickly undock
6180
40.4k
        ImGuiDockNode* node = window->DockNode;
6181
40.4k
        if (window->DockIsActive && node->IsHiddenTabBar() && !node->IsNoTabBar())
6182
0
        {
6183
0
            float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
6184
0
            float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
6185
0
            ImVec2 p = node->Pos;
6186
0
            ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
6187
0
            ImGuiID unhide_id = window->GetID("#UNHIDE");
6188
0
            KeepAliveID(unhide_id);
6189
0
            bool hovered, held;
6190
0
            if (ButtonBehavior(r, unhide_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren))
6191
0
                node->WantHiddenTabBarToggle = true;
6192
0
            else if (held && IsMouseDragging(0))
6193
0
                StartMouseMovingWindowOrNode(window, node, true);
6194
6195
            // FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
6196
0
            ImU32 col = GetColorU32(((held && hovered) || (node->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
6197
0
            window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
6198
0
        }
6199
6200
        // Scrollbars
6201
40.4k
        if (window->ScrollbarX)
6202
3.02k
            Scrollbar(ImGuiAxis_X);
6203
40.4k
        if (window->ScrollbarY)
6204
1.62k
            Scrollbar(ImGuiAxis_Y);
6205
6206
        // Render resize grips (after their input handling so we don't have a frame of latency)
6207
40.4k
        if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
6208
37.4k
        {
6209
74.9k
            for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
6210
37.4k
            {
6211
37.4k
                const ImU32 col = resize_grip_col[resize_grip_n];
6212
37.4k
                if ((col & IM_COL32_A_MASK) == 0)
6213
34.4k
                    continue;
6214
3.02k
                const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
6215
3.02k
                const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
6216
3.02k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
6217
3.02k
                window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
6218
3.02k
                window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
6219
3.02k
                window->DrawList->PathFillConvex(col);
6220
3.02k
            }
6221
37.4k
        }
6222
6223
        // Borders (for dock node host they will be rendered over after the tab bar)
6224
40.4k
        if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
6225
40.4k
            RenderWindowOuterBorders(window);
6226
40.4k
    }
6227
71.9k
}
6228
6229
// When inside a dock node, this is handled in DockNodeCalcTabBarLayout() instead.
6230
// Render title text, collapse button, close button
6231
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
6232
68.8k
{
6233
68.8k
    ImGuiContext& g = *GImGui;
6234
68.8k
    ImGuiStyle& style = g.Style;
6235
68.8k
    ImGuiWindowFlags flags = window->Flags;
6236
6237
68.8k
    const bool has_close_button = (p_open != NULL);
6238
68.8k
    const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
6239
6240
    // Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
6241
    // FIXME-NAV: Might want (or not?) to set the equivalent of ImGuiButtonFlags_NoNavFocus so that mouse clicks on standard title bar items don't necessarily set nav/keyboard ref?
6242
68.8k
    const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
6243
68.8k
    g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
6244
68.8k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
6245
6246
    // Layout buttons
6247
    // FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
6248
68.8k
    float pad_l = style.FramePadding.x;
6249
68.8k
    float pad_r = style.FramePadding.x;
6250
68.8k
    float button_sz = g.FontSize;
6251
68.8k
    ImVec2 close_button_pos;
6252
68.8k
    ImVec2 collapse_button_pos;
6253
68.8k
    if (has_close_button)
6254
0
    {
6255
0
        pad_r += button_sz;
6256
0
        close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6257
0
    }
6258
68.8k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
6259
0
    {
6260
0
        pad_r += button_sz;
6261
0
        collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
6262
0
    }
6263
68.8k
    if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
6264
68.8k
    {
6265
68.8k
        collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
6266
68.8k
        pad_l += button_sz;
6267
68.8k
    }
6268
6269
    // Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
6270
68.8k
    if (has_collapse_button)
6271
68.8k
        if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos, NULL))
6272
28
            window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
6273
6274
    // Close button
6275
68.8k
    if (has_close_button)
6276
0
        if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
6277
0
            *p_open = false;
6278
6279
68.8k
    window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
6280
68.8k
    g.CurrentItemFlags = item_flags_backup;
6281
6282
    // Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
6283
    // FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
6284
68.8k
    const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? button_sz * 0.80f : 0.0f;
6285
68.8k
    const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
6286
6287
    // As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
6288
    // while uncentered title text will still reach edges correctly.
6289
68.8k
    if (pad_l > style.FramePadding.x)
6290
68.8k
        pad_l += g.Style.ItemInnerSpacing.x;
6291
68.8k
    if (pad_r > style.FramePadding.x)
6292
0
        pad_r += g.Style.ItemInnerSpacing.x;
6293
68.8k
    if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
6294
0
    {
6295
0
        float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
6296
0
        float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
6297
0
        pad_l = ImMax(pad_l, pad_extend * centerness);
6298
0
        pad_r = ImMax(pad_r, pad_extend * centerness);
6299
0
    }
6300
6301
68.8k
    ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
6302
68.8k
    ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
6303
68.8k
    if (flags & ImGuiWindowFlags_UnsavedDocument)
6304
0
    {
6305
0
        ImVec2 marker_pos;
6306
0
        marker_pos.x = ImClamp(layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x + text_size.x, layout_r.Min.x, layout_r.Max.x);
6307
0
        marker_pos.y = (layout_r.Min.y + layout_r.Max.y) * 0.5f;
6308
0
        if (marker_pos.x > layout_r.Min.x)
6309
0
        {
6310
0
            RenderBullet(window->DrawList, marker_pos, GetColorU32(ImGuiCol_Text));
6311
0
            clip_r.Max.x = ImMin(clip_r.Max.x, marker_pos.x - (int)(marker_size_x * 0.5f));
6312
0
        }
6313
0
    }
6314
    //if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6315
    //if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
6316
68.8k
    RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
6317
68.8k
}
6318
6319
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
6320
71.9k
{
6321
71.9k
    window->ParentWindow = parent_window;
6322
71.9k
    window->RootWindow = window->RootWindowPopupTree = window->RootWindowDockTree = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
6323
71.9k
    if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
6324
3.02k
    {
6325
3.02k
        window->RootWindowDockTree = parent_window->RootWindowDockTree;
6326
3.02k
        if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
6327
3.02k
            window->RootWindow = parent_window->RootWindow;
6328
3.02k
    }
6329
71.9k
    if (parent_window && (flags & ImGuiWindowFlags_Popup))
6330
0
        window->RootWindowPopupTree = parent_window->RootWindowPopupTree;
6331
71.9k
    if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup))) // FIXME: simply use _NoTitleBar ?
6332
3.02k
        window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
6333
71.9k
    while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
6334
0
    {
6335
0
        IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
6336
0
        window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
6337
0
    }
6338
71.9k
}
6339
6340
// When a modal popup is open, newly created windows that want focus (i.e. are not popups and do not specify ImGuiWindowFlags_NoFocusOnAppearing)
6341
// should be positioned behind that modal window, unless the window was created inside the modal begin-stack.
6342
// In case of multiple stacked modals newly created window honors begin stack order and does not go below its own modal parent.
6343
// - Window             // FindBlockingModal() returns Modal1
6344
//   - Window           //                  .. returns Modal1
6345
//   - Modal1           //                  .. returns Modal2
6346
//      - Window        //                  .. returns Modal2
6347
//          - Window    //                  .. returns Modal2
6348
//          - Modal2    //                  .. returns Modal2
6349
static ImGuiWindow* ImGui::FindBlockingModal(ImGuiWindow* window)
6350
0
{
6351
0
    ImGuiContext& g = *GImGui;
6352
0
    if (g.OpenPopupStack.Size <= 0)
6353
0
        return NULL;
6354
6355
    // Find a modal that has common parent with specified window. Specified window should be positioned behind that modal.
6356
0
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
6357
0
    {
6358
0
        ImGuiWindow* popup_window = g.OpenPopupStack.Data[i].Window;
6359
0
        if (popup_window == NULL || !(popup_window->Flags & ImGuiWindowFlags_Modal))
6360
0
            continue;
6361
0
        if (!popup_window->Active && !popup_window->WasActive)      // Check WasActive, because this code may run before popup renders on current frame, also check Active to handle newly created windows.
6362
0
            continue;
6363
0
        if (IsWindowWithinBeginStackOf(window, popup_window))       // Window is rendered over last modal, no render order change needed.
6364
0
            break;
6365
0
        for (ImGuiWindow* parent = popup_window->ParentWindowInBeginStack->RootWindow; parent != NULL; parent = parent->ParentWindowInBeginStack->RootWindow)
6366
0
            if (IsWindowWithinBeginStackOf(window, parent))
6367
0
                return popup_window;                                // Place window above its begin stack parent.
6368
0
    }
6369
0
    return NULL;
6370
0
}
6371
6372
// Push a new Dear ImGui window to add widgets to.
6373
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
6374
// - Begin/End can be called multiple times during the frame with the same window name to append content.
6375
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
6376
//   You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
6377
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
6378
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
6379
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
6380
71.9k
{
6381
71.9k
    ImGuiContext& g = *GImGui;
6382
71.9k
    const ImGuiStyle& style = g.Style;
6383
71.9k
    IM_ASSERT(name != NULL && name[0] != '\0');     // Window name required
6384
71.9k
    IM_ASSERT(g.WithinFrameScope);                  // Forgot to call ImGui::NewFrame()
6385
71.9k
    IM_ASSERT(g.FrameCountEnded != g.FrameCount);   // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
6386
6387
    // Find or create
6388
71.9k
    ImGuiWindow* window = FindWindowByName(name);
6389
71.9k
    const bool window_just_created = (window == NULL);
6390
71.9k
    if (window_just_created)
6391
3
        window = CreateNewWindow(name, flags);
6392
6393
    // Automatically disable manual moving/resizing when NoInputs is set
6394
71.9k
    if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
6395
0
        flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
6396
6397
71.9k
    if (flags & ImGuiWindowFlags_NavFlattened)
6398
71.9k
        IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
6399
6400
71.9k
    const int current_frame = g.FrameCount;
6401
71.9k
    const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
6402
71.9k
    window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
6403
6404
    // Update the Appearing flag (note: the BeginDocked() path may also set this to true later)
6405
71.9k
    bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
6406
71.9k
    if (flags & ImGuiWindowFlags_Popup)
6407
0
    {
6408
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6409
0
        window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
6410
0
        window_just_activated_by_user |= (window != popup_ref.Window);
6411
0
    }
6412
6413
    // Update Flags, LastFrameActive, BeginOrderXXX fields
6414
71.9k
    const bool window_was_appearing = window->Appearing;
6415
71.9k
    if (first_begin_of_the_frame)
6416
71.9k
    {
6417
71.9k
        UpdateWindowInFocusOrderList(window, window_just_created, flags);
6418
71.9k
        window->Appearing = window_just_activated_by_user;
6419
71.9k
        if (window->Appearing)
6420
19
            SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6421
71.9k
        window->FlagsPreviousFrame = window->Flags;
6422
71.9k
        window->Flags = (ImGuiWindowFlags)flags;
6423
71.9k
        window->LastFrameActive = current_frame;
6424
71.9k
        window->LastTimeActive = (float)g.Time;
6425
71.9k
        window->BeginOrderWithinParent = 0;
6426
71.9k
        window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
6427
71.9k
    }
6428
0
    else
6429
0
    {
6430
0
        flags = window->Flags;
6431
0
    }
6432
6433
    // Docking
6434
    // (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
6435
71.9k
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
6436
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasDock)
6437
0
        SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
6438
71.9k
    if (first_begin_of_the_frame)
6439
71.9k
    {
6440
71.9k
        bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
6441
71.9k
        bool new_auto_dock_node = !has_dock_node && GetWindowAlwaysWantOwnTabBar(window);
6442
71.9k
        bool dock_node_was_visible = window->DockNodeIsVisible;
6443
71.9k
        bool dock_tab_was_visible = window->DockTabIsVisible;
6444
71.9k
        if (has_dock_node || new_auto_dock_node)
6445
0
        {
6446
0
            BeginDocked(window, p_open);
6447
0
            flags = window->Flags;
6448
0
            if (window->DockIsActive)
6449
0
            {
6450
0
                IM_ASSERT(window->DockNode != NULL);
6451
0
                g.NextWindowData.Flags &= ~ImGuiNextWindowDataFlags_HasSizeConstraint; // Docking currently override constraints
6452
0
            }
6453
6454
            // Amend the Appearing flag
6455
0
            if (window->DockTabIsVisible && !dock_tab_was_visible && dock_node_was_visible && !window->Appearing && !window_was_appearing)
6456
0
            {
6457
0
                window->Appearing = true;
6458
0
                SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
6459
0
            }
6460
0
        }
6461
71.9k
        else
6462
71.9k
        {
6463
71.9k
            window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
6464
71.9k
        }
6465
71.9k
    }
6466
6467
    // Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
6468
71.9k
    ImGuiWindow* parent_window_in_stack = (window->DockIsActive && window->DockNode->HostWindow) ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back().Window;
6469
71.9k
    ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
6470
71.9k
    IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
6471
6472
    // We allow window memory to be compacted so recreate the base stack when needed.
6473
71.9k
    if (window->IDStack.Size == 0)
6474
2
        window->IDStack.push_back(window->ID);
6475
6476
    // Add to stack
6477
    // We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
6478
71.9k
    g.CurrentWindow = window;
6479
71.9k
    ImGuiWindowStackData window_stack_data;
6480
71.9k
    window_stack_data.Window = window;
6481
71.9k
    window_stack_data.ParentLastItemDataBackup = g.LastItemData;
6482
71.9k
    window_stack_data.StackSizesOnBegin.SetToCurrentState();
6483
71.9k
    g.CurrentWindowStack.push_back(window_stack_data);
6484
71.9k
    if (flags & ImGuiWindowFlags_ChildMenu)
6485
0
        g.BeginMenuCount++;
6486
6487
    // Update ->RootWindow and others pointers (before any possible call to FocusWindow)
6488
71.9k
    if (first_begin_of_the_frame)
6489
71.9k
    {
6490
71.9k
        UpdateWindowParentAndRootLinks(window, flags, parent_window);
6491
71.9k
        window->ParentWindowInBeginStack = parent_window_in_stack;
6492
71.9k
    }
6493
6494
    // Add to focus scope stack
6495
71.9k
    PushFocusScope(window->ID);
6496
71.9k
    window->NavRootFocusScopeId = g.CurrentFocusScopeId;
6497
71.9k
    g.CurrentWindow = NULL;
6498
6499
    // Add to popup stack
6500
71.9k
    if (flags & ImGuiWindowFlags_Popup)
6501
0
    {
6502
0
        ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
6503
0
        popup_ref.Window = window;
6504
0
        popup_ref.ParentNavLayer = parent_window_in_stack->DC.NavLayerCurrent;
6505
0
        g.BeginPopupStack.push_back(popup_ref);
6506
0
        window->PopupId = popup_ref.PopupId;
6507
0
    }
6508
6509
    // Process SetNextWindow***() calls
6510
    // (FIXME: Consider splitting the HasXXX flags into X/Y components
6511
71.9k
    bool window_pos_set_by_api = false;
6512
71.9k
    bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
6513
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos)
6514
0
    {
6515
0
        window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
6516
0
        if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
6517
0
        {
6518
            // May be processed on the next frame if this is our first frame and we are measuring size
6519
            // FIXME: Look into removing the branch so everything can go through this same code path for consistency.
6520
0
            window->SetWindowPosVal = g.NextWindowData.PosVal;
6521
0
            window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
6522
0
            window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
6523
0
        }
6524
0
        else
6525
0
        {
6526
0
            SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
6527
0
        }
6528
0
    }
6529
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
6530
37.4k
    {
6531
37.4k
        window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
6532
37.4k
        window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
6533
37.4k
        SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
6534
37.4k
    }
6535
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
6536
0
    {
6537
0
        if (g.NextWindowData.ScrollVal.x >= 0.0f)
6538
0
        {
6539
0
            window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
6540
0
            window->ScrollTargetCenterRatio.x = 0.0f;
6541
0
        }
6542
0
        if (g.NextWindowData.ScrollVal.y >= 0.0f)
6543
0
        {
6544
0
            window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
6545
0
            window->ScrollTargetCenterRatio.y = 0.0f;
6546
0
        }
6547
0
    }
6548
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
6549
0
        window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
6550
71.9k
    else if (first_begin_of_the_frame)
6551
71.9k
        window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
6552
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasWindowClass)
6553
0
        window->WindowClass = g.NextWindowData.WindowClass;
6554
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
6555
0
        SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
6556
71.9k
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
6557
0
        FocusWindow(window);
6558
71.9k
    if (window->Appearing)
6559
19
        SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
6560
6561
    // When reusing window again multiple times a frame, just append content (don't need to setup again)
6562
71.9k
    if (first_begin_of_the_frame)
6563
71.9k
    {
6564
        // Initialize
6565
71.9k
        const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
6566
71.9k
        const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
6567
71.9k
        window->Active = true;
6568
71.9k
        window->HasCloseButton = (p_open != NULL);
6569
71.9k
        window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
6570
71.9k
        window->IDStack.resize(1);
6571
71.9k
        window->DrawList->_ResetForNewFrame();
6572
71.9k
        window->DC.CurrentTableIdx = -1;
6573
71.9k
        if (flags & ImGuiWindowFlags_DockNodeHost)
6574
0
        {
6575
0
            window->DrawList->ChannelsSplit(2);
6576
0
            window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG); // Render decorations on channel 1 as we will render the backgrounds manually later
6577
0
        }
6578
6579
        // Restore buffer capacity when woken from a compacted state, to avoid
6580
71.9k
        if (window->MemoryCompacted)
6581
2
            GcAwakeTransientWindowBuffers(window);
6582
6583
        // Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
6584
        // The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
6585
71.9k
        bool window_title_visible_elsewhere = false;
6586
71.9k
        if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
6587
0
            window_title_visible_elsewhere = true;
6588
71.9k
        else if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0)   // Window titles visible when using CTRL+TAB
6589
0
            window_title_visible_elsewhere = true;
6590
71.9k
        if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
6591
0
        {
6592
0
            size_t buf_len = (size_t)window->NameBufLen;
6593
0
            window->Name = ImStrdupcpy(window->Name, &buf_len, name);
6594
0
            window->NameBufLen = (int)buf_len;
6595
0
        }
6596
6597
        // UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
6598
6599
        // Update contents size from last frame for auto-fitting (or use explicit size)
6600
71.9k
        CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
6601
6602
        // FIXME: These flags are decremented before they are used. This means that in order to have these fields produce their intended behaviors
6603
        // for one frame we must set them to at least 2, which is counter-intuitive. HiddenFramesCannotSkipItems is a more complicated case because
6604
        // it has a single usage before this code block and may be set below before it is finally checked.
6605
71.9k
        if (window->HiddenFramesCanSkipItems > 0)
6606
716
            window->HiddenFramesCanSkipItems--;
6607
71.9k
        if (window->HiddenFramesCannotSkipItems > 0)
6608
2
            window->HiddenFramesCannotSkipItems--;
6609
71.9k
        if (window->HiddenFramesForRenderOnly > 0)
6610
0
            window->HiddenFramesForRenderOnly--;
6611
6612
        // Hide new windows for one frame until they calculate their size
6613
71.9k
        if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
6614
1
            window->HiddenFramesCannotSkipItems = 1;
6615
6616
        // Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
6617
        // We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
6618
71.9k
        if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
6619
0
        {
6620
0
            window->HiddenFramesCannotSkipItems = 1;
6621
0
            if (flags & ImGuiWindowFlags_AlwaysAutoResize)
6622
0
            {
6623
0
                if (!window_size_x_set_by_api)
6624
0
                    window->Size.x = window->SizeFull.x = 0.f;
6625
0
                if (!window_size_y_set_by_api)
6626
0
                    window->Size.y = window->SizeFull.y = 0.f;
6627
0
                window->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
6628
0
            }
6629
0
        }
6630
6631
        // SELECT VIEWPORT
6632
        // We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
6633
6634
71.9k
        WindowSelectViewport(window);
6635
71.9k
        SetCurrentViewport(window, window->Viewport);
6636
71.9k
        window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6637
71.9k
        SetCurrentWindow(window);
6638
71.9k
        flags = window->Flags;
6639
6640
        // LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
6641
        // We read Style data after the call to UpdateSelectWindowViewport() which might be swapping the style.
6642
6643
71.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
6644
3.02k
            window->WindowBorderSize = style.ChildBorderSize;
6645
68.8k
        else
6646
68.8k
            window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
6647
71.9k
        if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
6648
1.77k
            window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
6649
70.1k
        else
6650
70.1k
            window->WindowPadding = style.WindowPadding;
6651
6652
        // Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
6653
71.9k
        window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
6654
71.9k
        window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
6655
6656
71.9k
        bool use_current_size_for_scrollbar_x = window_just_created;
6657
71.9k
        bool use_current_size_for_scrollbar_y = window_just_created;
6658
6659
        // Collapse window by double-clicking on title bar
6660
        // At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
6661
71.9k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
6662
68.8k
        {
6663
            // We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
6664
68.8k
            ImRect title_bar_rect = window->TitleBarRect();
6665
68.8k
            if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseClickedCount[0] == 2)
6666
5
                window->WantCollapseToggle = true;
6667
68.8k
            if (window->WantCollapseToggle)
6668
33
            {
6669
33
                window->Collapsed = !window->Collapsed;
6670
33
                if (!window->Collapsed)
6671
16
                    use_current_size_for_scrollbar_y = true;
6672
33
                MarkIniSettingsDirty(window);
6673
33
            }
6674
68.8k
        }
6675
3.02k
        else
6676
3.02k
        {
6677
3.02k
            window->Collapsed = false;
6678
3.02k
        }
6679
71.9k
        window->WantCollapseToggle = false;
6680
6681
        // SIZE
6682
6683
        // Outer Decoration Sizes
6684
        // (we need to clear ScrollbarSize immediatly as CalcWindowAutoFitSize() needs it and can be called from other locations).
6685
71.9k
        const ImVec2 scrollbar_sizes_from_last_frame = window->ScrollbarSizes;
6686
71.9k
        window->DecoOuterSizeX1 = 0.0f;
6687
71.9k
        window->DecoOuterSizeX2 = 0.0f;
6688
71.9k
        window->DecoOuterSizeY1 = window->TitleBarHeight() + window->MenuBarHeight();
6689
71.9k
        window->DecoOuterSizeY2 = 0.0f;
6690
71.9k
        window->ScrollbarSizes = ImVec2(0.0f, 0.0f);
6691
6692
        // Calculate auto-fit size, handle automatic resize
6693
71.9k
        const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
6694
71.9k
        if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
6695
0
        {
6696
            // Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
6697
0
            if (!window_size_x_set_by_api)
6698
0
            {
6699
0
                window->SizeFull.x = size_auto_fit.x;
6700
0
                use_current_size_for_scrollbar_x = true;
6701
0
            }
6702
0
            if (!window_size_y_set_by_api)
6703
0
            {
6704
0
                window->SizeFull.y = size_auto_fit.y;
6705
0
                use_current_size_for_scrollbar_y = true;
6706
0
            }
6707
0
        }
6708
71.9k
        else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
6709
2
        {
6710
            // Auto-fit may only grow window during the first few frames
6711
            // We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
6712
2
            if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
6713
2
            {
6714
2
                window->SizeFull.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
6715
2
                use_current_size_for_scrollbar_x = true;
6716
2
            }
6717
2
            if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
6718
2
            {
6719
2
                window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
6720
2
                use_current_size_for_scrollbar_y = true;
6721
2
            }
6722
2
            if (!window->Collapsed)
6723
2
                MarkIniSettingsDirty(window);
6724
2
        }
6725
6726
        // Apply minimum/maximum window size constraints and final size
6727
71.9k
        window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
6728
71.9k
        window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
6729
6730
        // POSITION
6731
6732
        // Popup latch its initial position, will position itself when it appears next frame
6733
71.9k
        if (window_just_activated_by_user)
6734
19
        {
6735
19
            window->AutoPosLastDirection = ImGuiDir_None;
6736
19
            if ((flags & ImGuiWindowFlags_Popup) != 0 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
6737
0
                window->Pos = g.BeginPopupStack.back().OpenPopupPos;
6738
19
        }
6739
6740
        // Position child window
6741
71.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
6742
3.02k
        {
6743
3.02k
            IM_ASSERT(parent_window && parent_window->Active);
6744
3.02k
            window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
6745
3.02k
            parent_window->DC.ChildWindows.push_back(window);
6746
3.02k
            if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
6747
3.02k
                window->Pos = parent_window->DC.CursorPos;
6748
3.02k
        }
6749
6750
71.9k
        const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
6751
71.9k
        if (window_pos_with_pivot)
6752
0
            SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
6753
71.9k
        else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
6754
0
            window->Pos = FindBestWindowPosForPopup(window);
6755
71.9k
        else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
6756
0
            window->Pos = FindBestWindowPosForPopup(window);
6757
71.9k
        else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
6758
0
            window->Pos = FindBestWindowPosForPopup(window);
6759
6760
        // Late create viewport if we don't fit within our current host viewport.
6761
71.9k
        if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_Minimized))
6762
0
            if (!window->Viewport->GetMainRect().Contains(window->Rect()))
6763
0
            {
6764
                // This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
6765
                //ImGuiViewport* old_viewport = window->Viewport;
6766
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
6767
6768
                // FIXME-DPI
6769
                //IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
6770
0
                SetCurrentViewport(window, window->Viewport);
6771
0
                window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
6772
0
                SetCurrentWindow(window);
6773
0
            }
6774
6775
71.9k
        if (window->ViewportOwned)
6776
0
            WindowSyncOwnedViewport(window, parent_window_in_stack);
6777
6778
        // Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
6779
        // When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
6780
71.9k
        ImRect viewport_rect(window->Viewport->GetMainRect());
6781
71.9k
        ImRect viewport_work_rect(window->Viewport->GetWorkRect());
6782
71.9k
        ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
6783
71.9k
        ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
6784
6785
        // Clamp position/size so window stays visible within its viewport or monitor
6786
        // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
6787
        // FIXME: Similar to code in GetWindowAllowedExtentRect()
6788
71.9k
        if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow))
6789
68.8k
        {
6790
68.8k
            if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
6791
68.8k
            {
6792
68.8k
                ClampWindowPos(window, visibility_rect);
6793
68.8k
            }
6794
0
            else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
6795
0
            {
6796
                // Lost windows (e.g. a monitor disconnected) will naturally moved to the fallback/dummy monitor aka the main viewport.
6797
0
                const ImGuiPlatformMonitor* monitor = GetViewportPlatformMonitor(window->Viewport);
6798
0
                visibility_rect.Min = monitor->WorkPos + visibility_padding;
6799
0
                visibility_rect.Max = monitor->WorkPos + monitor->WorkSize - visibility_padding;
6800
0
                ClampWindowPos(window, visibility_rect);
6801
0
            }
6802
68.8k
        }
6803
71.9k
        window->Pos = ImFloor(window->Pos);
6804
6805
        // Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
6806
        // Large values tend to lead to variety of artifacts and are not recommended.
6807
71.9k
        if (window->ViewportOwned || window->DockIsActive)
6808
0
            window->WindowRounding = 0.0f;
6809
71.9k
        else
6810
71.9k
            window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
6811
6812
        // For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
6813
        //if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
6814
        //    window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
6815
6816
        // Apply window focus (new and reactivated windows are moved to front)
6817
71.9k
        bool want_focus = false;
6818
71.9k
        if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
6819
19
        {
6820
19
            if (flags & ImGuiWindowFlags_Popup)
6821
0
                want_focus = true;
6822
19
            else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
6823
2
                want_focus = true;
6824
6825
19
            ImGuiWindow* modal = GetTopMostPopupModal();
6826
19
            if (modal != NULL && !IsWindowWithinBeginStackOf(window, modal))
6827
0
            {
6828
                // Avoid focusing a window that is created outside of active modal. This will prevent active modal from being closed.
6829
                // Since window is not focused it would reappear at the same display position like the last time it was visible.
6830
                // In case of completely new windows it would go to the top (over current modal), but input to such window would still be blocked by modal.
6831
                // Position window behind a modal that is not a begin-parent of this window.
6832
0
                want_focus = false;
6833
0
                if (window == window->RootWindow)
6834
0
                {
6835
0
                    ImGuiWindow* blocking_modal = FindBlockingModal(window);
6836
0
                    IM_ASSERT(blocking_modal != NULL);
6837
0
                    BringWindowToDisplayBehind(window, blocking_modal);
6838
0
                }
6839
0
            }
6840
19
        }
6841
6842
        // [Test Engine] Register whole window in the item system
6843
#ifdef IMGUI_ENABLE_TEST_ENGINE
6844
        if (g.TestEngineHookItems)
6845
        {
6846
            IM_ASSERT(window->IDStack.Size == 1);
6847
            window->IDStack.Size = 0; // As window->IDStack[0] == window->ID here, make sure TestEngine doesn't erroneously see window as parent of itself.
6848
            IMGUI_TEST_ENGINE_ITEM_ADD(window->Rect(), window->ID);
6849
            IMGUI_TEST_ENGINE_ITEM_INFO(window->ID, window->Name, (g.HoveredWindow == window) ? ImGuiItemStatusFlags_HoveredRect : 0);
6850
            window->IDStack.Size = 1;
6851
        }
6852
#endif
6853
6854
        // Decide if we are going to handle borders and resize grips
6855
71.9k
        const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
6856
6857
        // Handle manual resize: Resize Grips, Borders, Gamepad
6858
71.9k
        int border_held = -1;
6859
71.9k
        ImU32 resize_grip_col[4] = {};
6860
71.9k
        const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
6861
71.9k
        const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
6862
71.9k
        if (handle_borders_and_resize_grips && !window->Collapsed)
6863
40.4k
            if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
6864
7
                use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
6865
71.9k
        window->ResizeBorderHeld = (signed char)border_held;
6866
6867
        // Synchronize window --> viewport again and one last time (clamping and manual resize may have affected either)
6868
71.9k
        if (window->ViewportOwned)
6869
0
        {
6870
0
            if (!window->Viewport->PlatformRequestMove)
6871
0
                window->Viewport->Pos = window->Pos;
6872
0
            if (!window->Viewport->PlatformRequestResize)
6873
0
                window->Viewport->Size = window->Size;
6874
0
            window->Viewport->UpdateWorkRect();
6875
0
            viewport_rect = window->Viewport->GetMainRect();
6876
0
        }
6877
6878
        // Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
6879
71.9k
        window->ViewportPos = window->Viewport->Pos;
6880
6881
        // SCROLLBAR VISIBILITY
6882
6883
        // Update scrollbar visibility (based on the Size that was effective during last frame or the auto-resized Size).
6884
71.9k
        if (!window->Collapsed)
6885
40.4k
        {
6886
            // When reading the current size we need to read it after size constraints have been applied.
6887
            // Intentionally use previous frame values for InnerRect and ScrollbarSizes.
6888
            // And when we use window->DecorationUp here it doesn't have ScrollbarSizes.y applied yet.
6889
40.4k
            ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2));
6890
40.4k
            ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + scrollbar_sizes_from_last_frame;
6891
40.4k
            ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
6892
40.4k
            float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
6893
40.4k
            float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
6894
            //bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
6895
40.4k
            window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
6896
40.4k
            window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
6897
40.4k
            if (window->ScrollbarX && !window->ScrollbarY)
6898
2.06k
                window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
6899
40.4k
            window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
6900
6901
            // Amend the partially filled window->DecorationXXX values.
6902
40.4k
            window->DecoOuterSizeX2 += window->ScrollbarSizes.x;
6903
40.4k
            window->DecoOuterSizeY2 += window->ScrollbarSizes.y;
6904
40.4k
        }
6905
6906
        // UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
6907
        // Update various regions. Variables they depend on should be set above in this function.
6908
        // We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
6909
6910
        // Outer rectangle
6911
        // Not affected by window border size. Used by:
6912
        // - FindHoveredWindow() (w/ extra padding when border resize is enabled)
6913
        // - Begin() initial clipping rect for drawing window background and borders.
6914
        // - Begin() clipping whole child
6915
71.9k
        const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
6916
71.9k
        const ImRect outer_rect = window->Rect();
6917
71.9k
        const ImRect title_bar_rect = window->TitleBarRect();
6918
71.9k
        window->OuterRectClipped = outer_rect;
6919
71.9k
        if (window->DockIsActive)
6920
0
            window->OuterRectClipped.Min.y += window->TitleBarHeight();
6921
71.9k
        window->OuterRectClipped.ClipWith(host_rect);
6922
6923
        // Inner rectangle
6924
        // Not affected by window border size. Used by:
6925
        // - InnerClipRect
6926
        // - ScrollToRectEx()
6927
        // - NavUpdatePageUpPageDown()
6928
        // - Scrollbar()
6929
71.9k
        window->InnerRect.Min.x = window->Pos.x + window->DecoOuterSizeX1;
6930
71.9k
        window->InnerRect.Min.y = window->Pos.y + window->DecoOuterSizeY1;
6931
71.9k
        window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->DecoOuterSizeX2;
6932
71.9k
        window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->DecoOuterSizeY2;
6933
6934
        // Inner clipping rectangle.
6935
        // Will extend a little bit outside the normal work region.
6936
        // This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
6937
        // Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
6938
        // Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
6939
        // Affected by window/frame border size. Used by:
6940
        // - Begin() initial clip rect
6941
71.9k
        float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
6942
71.9k
        window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6943
71.9k
        window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
6944
71.9k
        window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
6945
71.9k
        window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
6946
71.9k
        window->InnerClipRect.ClipWithFull(host_rect);
6947
6948
        // Default item width. Make it proportional to window size if window manually resizes
6949
71.9k
        if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
6950
71.9k
            window->ItemWidthDefault = ImFloor(window->Size.x * 0.65f);
6951
16
        else
6952
16
            window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
6953
6954
        // SCROLLING
6955
6956
        // Lock down maximum scrolling
6957
        // The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
6958
        // for right/bottom aligned items without creating a scrollbar.
6959
71.9k
        window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
6960
71.9k
        window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
6961
6962
        // Apply scrolling
6963
71.9k
        window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
6964
71.9k
        window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
6965
71.9k
        window->DecoInnerSizeX1 = window->DecoInnerSizeY1 = 0.0f;
6966
6967
        // DRAWING
6968
6969
        // Setup draw list and outer clipping rectangle
6970
71.9k
        IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
6971
71.9k
        window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
6972
71.9k
        PushClipRect(host_rect.Min, host_rect.Max, false);
6973
6974
        // Child windows can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call (since 1.71)
6975
        // When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
6976
        // FIXME: User code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected (github #4493)
6977
71.9k
        const bool is_undocked_or_docked_visible = !window->DockIsActive || window->DockTabIsVisible;
6978
71.9k
        if (is_undocked_or_docked_visible)
6979
71.9k
        {
6980
71.9k
            bool render_decorations_in_parent = false;
6981
71.9k
            if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
6982
3.02k
            {
6983
                // - We test overlap with the previous child window only (testing all would end up being O(log N) not a good investment here)
6984
                // - We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping childs
6985
3.02k
                ImGuiWindow* previous_child = parent_window->DC.ChildWindows.Size >= 2 ? parent_window->DC.ChildWindows[parent_window->DC.ChildWindows.Size - 2] : NULL;
6986
3.02k
                bool previous_child_overlapping = previous_child ? previous_child->Rect().Overlaps(window->Rect()) : false;
6987
3.02k
                bool parent_is_empty = parent_window->DrawList->VtxBuffer.Size > 0;
6988
3.02k
                if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_is_empty && !previous_child_overlapping)
6989
3.02k
                    render_decorations_in_parent = true;
6990
3.02k
            }
6991
71.9k
            if (render_decorations_in_parent)
6992
3.02k
                window->DrawList = parent_window->DrawList;
6993
6994
            // Handle title bar, scrollbar, resize grips and resize borders
6995
71.9k
            const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
6996
71.9k
            const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
6997
71.9k
            RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, handle_borders_and_resize_grips, resize_grip_count, resize_grip_col, resize_grip_draw_size);
6998
6999
71.9k
            if (render_decorations_in_parent)
7000
3.02k
                window->DrawList = &window->DrawListInst;
7001
71.9k
        }
7002
7003
        // UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
7004
7005
        // Work rectangle.
7006
        // Affected by window padding and border size. Used by:
7007
        // - Columns() for right-most edge
7008
        // - TreeNode(), CollapsingHeader() for right-most edge
7009
        // - BeginTabBar() for right-most edge
7010
71.9k
        const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
7011
71.9k
        const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
7012
71.9k
        const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7013
71.9k
        const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7014
71.9k
        window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
7015
71.9k
        window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
7016
71.9k
        window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
7017
71.9k
        window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
7018
71.9k
        window->ParentWorkRect = window->WorkRect;
7019
7020
        // [LEGACY] Content Region
7021
        // FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
7022
        // Used by:
7023
        // - Mouse wheel scrolling + many other things
7024
71.9k
        window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x + window->DecoOuterSizeX1;
7025
71.9k
        window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->DecoOuterSizeY1;
7026
71.9k
        window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - (window->DecoOuterSizeX1 + window->DecoOuterSizeX2)));
7027
71.9k
        window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - (window->DecoOuterSizeY1 + window->DecoOuterSizeY2)));
7028
7029
        // Setup drawing context
7030
        // (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
7031
71.9k
        window->DC.Indent.x = window->DecoOuterSizeX1 + window->WindowPadding.x - window->Scroll.x;
7032
71.9k
        window->DC.GroupOffset.x = 0.0f;
7033
71.9k
        window->DC.ColumnsOffset.x = 0.0f;
7034
7035
        // Record the loss of precision of CursorStartPos which can happen due to really large scrolling amount.
7036
        // This is used by clipper to compensate and fix the most common use case of large scroll area. Easy and cheap, next best thing compared to switching everything to double or ImU64.
7037
71.9k
        double start_pos_highp_x = (double)window->Pos.x + window->WindowPadding.x - (double)window->Scroll.x + window->DecoOuterSizeX1 + window->DC.ColumnsOffset.x;
7038
71.9k
        double start_pos_highp_y = (double)window->Pos.y + window->WindowPadding.y - (double)window->Scroll.y + window->DecoOuterSizeY1;
7039
71.9k
        window->DC.CursorStartPos  = ImVec2((float)start_pos_highp_x, (float)start_pos_highp_y);
7040
71.9k
        window->DC.CursorStartPosLossyness = ImVec2((float)(start_pos_highp_x - window->DC.CursorStartPos.x), (float)(start_pos_highp_y - window->DC.CursorStartPos.y));
7041
71.9k
        window->DC.CursorPos = window->DC.CursorStartPos;
7042
71.9k
        window->DC.CursorPosPrevLine = window->DC.CursorPos;
7043
71.9k
        window->DC.CursorMaxPos = window->DC.CursorStartPos;
7044
71.9k
        window->DC.IdealMaxPos = window->DC.CursorStartPos;
7045
71.9k
        window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
7046
71.9k
        window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
7047
71.9k
        window->DC.IsSameLine = window->DC.IsSetPos = false;
7048
7049
71.9k
        window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
7050
71.9k
        window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
7051
71.9k
        window->DC.NavLayersActiveMaskNext = 0x00;
7052
71.9k
        window->DC.NavHideHighlightOneFrame = false;
7053
71.9k
        window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
7054
7055
71.9k
        window->DC.MenuBarAppending = false;
7056
71.9k
        window->DC.MenuColumns.Update(style.ItemSpacing.x, window_just_activated_by_user);
7057
71.9k
        window->DC.TreeDepth = 0;
7058
71.9k
        window->DC.TreeJumpToParentOnPopMask = 0x00;
7059
71.9k
        window->DC.ChildWindows.resize(0);
7060
71.9k
        window->DC.StateStorage = &window->StateStorage;
7061
71.9k
        window->DC.CurrentColumns = NULL;
7062
71.9k
        window->DC.LayoutType = ImGuiLayoutType_Vertical;
7063
71.9k
        window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
7064
7065
71.9k
        window->DC.ItemWidth = window->ItemWidthDefault;
7066
71.9k
        window->DC.TextWrapPos = -1.0f; // disabled
7067
71.9k
        window->DC.ItemWidthStack.resize(0);
7068
71.9k
        window->DC.TextWrapPosStack.resize(0);
7069
7070
71.9k
        if (window->AutoFitFramesX > 0)
7071
2
            window->AutoFitFramesX--;
7072
71.9k
        if (window->AutoFitFramesY > 0)
7073
2
            window->AutoFitFramesY--;
7074
7075
        // Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
7076
71.9k
        if (want_focus)
7077
2
        {
7078
2
            FocusWindow(window);
7079
2
            NavInitWindow(window, false); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
7080
2
        }
7081
7082
        // Close requested by platform window
7083
71.9k
        if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
7084
0
        {
7085
0
            if (!window->DockIsActive || window->DockTabIsVisible)
7086
0
            {
7087
0
                window->Viewport->PlatformRequestClose = false;
7088
0
                g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
7089
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' PlatformRequestClose\n", window->Name);
7090
0
                *p_open = false;
7091
0
            }
7092
0
        }
7093
7094
        // Title bar
7095
71.9k
        if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
7096
68.8k
            RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
7097
7098
        // Clear hit test shape every frame
7099
71.9k
        window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
7100
7101
        // Pressing CTRL+C while holding on a window copy its content to the clipboard
7102
        // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
7103
        // Maybe we can support CTRL+C on every element?
7104
        /*
7105
        //if (g.NavWindow == window && g.ActiveId == 0)
7106
        if (g.ActiveId == window->MoveId)
7107
            if (g.IO.KeyCtrl && IsKeyPressed(ImGuiKey_C))
7108
                LogToClipboard();
7109
        */
7110
7111
71.9k
        if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
7112
71.9k
        {
7113
            // Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
7114
            // We need to do this _before_ we overwrite window->DC.LastItemId below because BeginDockableDragDropSource() also overwrites it.
7115
71.9k
            if ((g.MovingWindow == window) && (g.IO.ConfigDockingWithShift == g.IO.KeyShift))
7116
120
                if ((window->RootWindowDockTree->Flags & ImGuiWindowFlags_NoDocking) == 0)
7117
120
                    BeginDockableDragDropSource(window);
7118
7119
            // Docking: Any dockable window can act as a target. For dock node hosts we call BeginDockableDragDropTarget() in DockNodeUpdate() instead.
7120
71.9k
            if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
7121
216
                if (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != window)
7122
140
                    if ((window == window->RootWindowDockTree) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
7123
140
                        BeginDockableDragDropTarget(window);
7124
71.9k
        }
7125
7126
        // We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
7127
        // This is useful to allow creating context menus on title bar only, etc.
7128
71.9k
        if (window->DockIsActive)
7129
0
            SetLastItemData(window->MoveId, g.CurrentItemFlags, window->DockTabItemStatusFlags, window->DockTabItemRect);
7130
71.9k
        else
7131
71.9k
            SetLastItemData(window->MoveId, g.CurrentItemFlags, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
7132
7133
        // [DEBUG]
7134
71.9k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
7135
71.9k
        if (g.DebugLocateId != 0 && (window->ID == g.DebugLocateId || window->MoveId == g.DebugLocateId))
7136
0
            DebugLocateItemResolveWithLastItem();
7137
71.9k
#endif
7138
7139
        // [Test Engine] Register title bar / tab
7140
#ifdef IMGUI_ENABLE_TEST_ENGINE
7141
        if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
7142
            IMGUI_TEST_ENGINE_ITEM_ADD(g.LastItemData.Rect, g.LastItemData.ID);
7143
#endif
7144
71.9k
    }
7145
0
    else
7146
0
    {
7147
        // Append
7148
0
        SetCurrentViewport(window, window->Viewport);
7149
0
        SetCurrentWindow(window);
7150
0
    }
7151
7152
71.9k
    if (!(flags & ImGuiWindowFlags_DockNodeHost))
7153
71.9k
        PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
7154
7155
    // Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
7156
71.9k
    window->WriteAccessed = false;
7157
71.9k
    window->BeginCount++;
7158
71.9k
    g.NextWindowData.ClearFlags();
7159
7160
    // Update visibility
7161
71.9k
    if (first_begin_of_the_frame)
7162
71.9k
    {
7163
        // When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesCannotSkipItems.
7164
        // This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
7165
        // This is analogous to regular windows being hidden from one frame.
7166
        // It is especially important as e.g. nested TabBars would otherwise generate flicker in the form of one empty frame, or focus requests won't be processed.
7167
71.9k
        if (window->DockIsActive && !window->DockTabIsVisible)
7168
0
        {
7169
0
            if (window->LastFrameJustFocused == g.FrameCount)
7170
0
                window->HiddenFramesCannotSkipItems = 1;
7171
0
            else
7172
0
                window->HiddenFramesCanSkipItems = 1;
7173
0
        }
7174
7175
71.9k
        if (flags & ImGuiWindowFlags_ChildWindow)
7176
3.02k
        {
7177
            // Child window can be out of sight and have "negative" clip windows.
7178
            // Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
7179
3.02k
            IM_ASSERT((flags& ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
7180
3.02k
            if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
7181
3.02k
            {
7182
3.02k
                const bool nav_request = (flags & ImGuiWindowFlags_NavFlattened) && (g.NavAnyRequest && g.NavWindow && g.NavWindow->RootWindowForNav == window->RootWindowForNav);
7183
3.02k
                if (!g.LogEnabled && !nav_request)
7184
3.02k
                    if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
7185
716
                        window->HiddenFramesCanSkipItems = 1;
7186
3.02k
            }
7187
7188
            // Hide along with parent or if parent is collapsed
7189
3.02k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
7190
0
                window->HiddenFramesCanSkipItems = 1;
7191
3.02k
            if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
7192
1
                window->HiddenFramesCannotSkipItems = 1;
7193
3.02k
        }
7194
7195
        // Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
7196
71.9k
        if (style.Alpha <= 0.0f)
7197
0
            window->HiddenFramesCanSkipItems = 1;
7198
7199
        // Update the Hidden flag
7200
71.9k
        bool hidden_regular = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
7201
71.9k
        window->Hidden = hidden_regular || (window->HiddenFramesForRenderOnly > 0);
7202
7203
        // Disable inputs for requested number of frames
7204
71.9k
        if (window->DisableInputsFrames > 0)
7205
0
        {
7206
0
            window->DisableInputsFrames--;
7207
0
            window->Flags |= ImGuiWindowFlags_NoInputs;
7208
0
        }
7209
7210
        // Update the SkipItems flag, used to early out of all items functions (no layout required)
7211
71.9k
        bool skip_items = false;
7212
71.9k
        if (window->Collapsed || !window->Active || hidden_regular)
7213
32.1k
            if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
7214
32.1k
                skip_items = true;
7215
71.9k
        window->SkipItems = skip_items;
7216
7217
        // Restore NavLayersActiveMaskNext to previous value when not visible, so a CTRL+Tab back can use a safe value.
7218
71.9k
        if (window->SkipItems)
7219
32.1k
            window->DC.NavLayersActiveMaskNext = window->DC.NavLayersActiveMask;
7220
7221
        // Sanity check: there are two spots which can set Appearing = true
7222
        // - when 'window_just_activated_by_user' is set -> HiddenFramesCannotSkipItems is set -> SkipItems always false
7223
        // - in BeginDocked() path when DockNodeIsVisible == DockTabIsVisible == true -> hidden _should_ be all zero // FIXME: Not formally proven, hence the assert.
7224
71.9k
        if (window->SkipItems && !window->Appearing)
7225
71.9k
            IM_ASSERT(window->Appearing == false); // Please report on GitHub if this triggers: https://github.com/ocornut/imgui/issues/4177
7226
71.9k
    }
7227
7228
71.9k
    return !window->SkipItems;
7229
71.9k
}
7230
7231
void ImGui::End()
7232
71.9k
{
7233
71.9k
    ImGuiContext& g = *GImGui;
7234
71.9k
    ImGuiWindow* window = g.CurrentWindow;
7235
7236
    // Error checking: verify that user hasn't called End() too many times!
7237
71.9k
    if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
7238
0
    {
7239
0
        IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
7240
0
        return;
7241
0
    }
7242
71.9k
    IM_ASSERT(g.CurrentWindowStack.Size > 0);
7243
7244
    // Error checking: verify that user doesn't directly call End() on a child window.
7245
71.9k
    if ((window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost) && !window->DockIsActive)
7246
71.9k
        IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
7247
7248
    // Close anything that is open
7249
71.9k
    if (window->DC.CurrentColumns)
7250
0
        EndColumns();
7251
71.9k
    if (!(window->Flags & ImGuiWindowFlags_DockNodeHost))   // Pop inner window clip rectangle
7252
71.9k
        PopClipRect();
7253
71.9k
    PopFocusScope();
7254
7255
    // Stop logging
7256
71.9k
    if (!(window->Flags & ImGuiWindowFlags_ChildWindow))    // FIXME: add more options for scope of logging
7257
68.8k
        LogFinish();
7258
7259
71.9k
    if (window->DC.IsSetPos)
7260
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
7261
7262
    // Docking: report contents sizes to parent to allow for auto-resize
7263
71.9k
    if (window->DockNode && window->DockTabIsVisible)
7264
0
        if (ImGuiWindow* host_window = window->DockNode->HostWindow)         // FIXME-DOCK
7265
0
            host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
7266
7267
    // Pop from window stack
7268
71.9k
    g.LastItemData = g.CurrentWindowStack.back().ParentLastItemDataBackup;
7269
71.9k
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
7270
0
        g.BeginMenuCount--;
7271
71.9k
    if (window->Flags & ImGuiWindowFlags_Popup)
7272
0
        g.BeginPopupStack.pop_back();
7273
71.9k
    g.CurrentWindowStack.back().StackSizesOnBegin.CompareWithCurrentState();
7274
71.9k
    g.CurrentWindowStack.pop_back();
7275
71.9k
    SetCurrentWindow(g.CurrentWindowStack.Size == 0 ? NULL : g.CurrentWindowStack.back().Window);
7276
71.9k
    if (g.CurrentWindow)
7277
37.4k
        SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
7278
71.9k
}
7279
7280
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
7281
1.37k
{
7282
1.37k
    ImGuiContext& g = *GImGui;
7283
1.37k
    IM_ASSERT(window == window->RootWindow);
7284
7285
1.37k
    const int cur_order = window->FocusOrder;
7286
1.37k
    IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
7287
1.37k
    if (g.WindowsFocusOrder.back() == window)
7288
1.37k
        return;
7289
7290
0
    const int new_order = g.WindowsFocusOrder.Size - 1;
7291
0
    for (int n = cur_order; n < new_order; n++)
7292
0
    {
7293
0
        g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
7294
0
        g.WindowsFocusOrder[n]->FocusOrder--;
7295
0
        IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
7296
0
    }
7297
0
    g.WindowsFocusOrder[new_order] = window;
7298
0
    window->FocusOrder = (short)new_order;
7299
0
}
7300
7301
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
7302
1.37k
{
7303
1.37k
    ImGuiContext& g = *GImGui;
7304
1.37k
    ImGuiWindow* current_front_window = g.Windows.back();
7305
1.37k
    if (current_front_window == window || current_front_window->RootWindowDockTree == window) // Cheap early out (could be better)
7306
1.37k
        return;
7307
0
    for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
7308
0
        if (g.Windows[i] == window)
7309
0
        {
7310
0
            memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
7311
0
            g.Windows[g.Windows.Size - 1] = window;
7312
0
            break;
7313
0
        }
7314
0
}
7315
7316
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
7317
0
{
7318
0
    ImGuiContext& g = *GImGui;
7319
0
    if (g.Windows[0] == window)
7320
0
        return;
7321
0
    for (int i = 0; i < g.Windows.Size; i++)
7322
0
        if (g.Windows[i] == window)
7323
0
        {
7324
0
            memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
7325
0
            g.Windows[0] = window;
7326
0
            break;
7327
0
        }
7328
0
}
7329
7330
void ImGui::BringWindowToDisplayBehind(ImGuiWindow* window, ImGuiWindow* behind_window)
7331
0
{
7332
0
    IM_ASSERT(window != NULL && behind_window != NULL);
7333
0
    ImGuiContext& g = *GImGui;
7334
0
    window = window->RootWindow;
7335
0
    behind_window = behind_window->RootWindow;
7336
0
    int pos_wnd = FindWindowDisplayIndex(window);
7337
0
    int pos_beh = FindWindowDisplayIndex(behind_window);
7338
0
    if (pos_wnd < pos_beh)
7339
0
    {
7340
0
        size_t copy_bytes = (pos_beh - pos_wnd - 1) * sizeof(ImGuiWindow*);
7341
0
        memmove(&g.Windows.Data[pos_wnd], &g.Windows.Data[pos_wnd + 1], copy_bytes);
7342
0
        g.Windows[pos_beh - 1] = window;
7343
0
    }
7344
0
    else
7345
0
    {
7346
0
        size_t copy_bytes = (pos_wnd - pos_beh) * sizeof(ImGuiWindow*);
7347
0
        memmove(&g.Windows.Data[pos_beh + 1], &g.Windows.Data[pos_beh], copy_bytes);
7348
0
        g.Windows[pos_beh] = window;
7349
0
    }
7350
0
}
7351
7352
int ImGui::FindWindowDisplayIndex(ImGuiWindow* window)
7353
0
{
7354
0
    ImGuiContext& g = *GImGui;
7355
0
    return g.Windows.index_from_ptr(g.Windows.find(window));
7356
0
}
7357
7358
// Moving window to front of display and set focus (which happens to be back of our sorted list)
7359
void ImGui::FocusWindow(ImGuiWindow* window)
7360
7.26k
{
7361
7.26k
    ImGuiContext& g = *GImGui;
7362
7363
7.26k
    if (g.NavWindow != window)
7364
1.82k
    {
7365
1.82k
        SetNavWindow(window);
7366
1.82k
        if (window && g.NavDisableMouseHover)
7367
112
            g.NavMousePosDirty = true;
7368
1.82k
        g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
7369
1.82k
        g.NavLayer = ImGuiNavLayer_Main;
7370
1.82k
        g.NavFocusScopeId = window ? window->NavRootFocusScopeId : 0;
7371
1.82k
        g.NavIdIsAlive = false;
7372
7373
        // Close popups if any
7374
1.82k
        ClosePopupsOverWindow(window, false);
7375
1.82k
    }
7376
7377
    // Move the root window to the top of the pile
7378
7.26k
    IM_ASSERT(window == NULL || window->RootWindowDockTree != NULL);
7379
7.26k
    ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL;
7380
7.26k
    ImGuiWindow* display_front_window = window ? window->RootWindowDockTree : NULL;
7381
7.26k
    ImGuiDockNode* dock_node = window ? window->DockNode : NULL;
7382
7.26k
    bool active_id_window_is_dock_node_host = (g.ActiveIdWindow && dock_node && dock_node->HostWindow == g.ActiveIdWindow);
7383
7384
    // Steal active widgets. Some of the cases it triggers includes:
7385
    // - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
7386
    // - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
7387
    // - Using dock host items (tab, collapse button) can trigger this before we redirect the ActiveIdWindow toward the child window.
7388
7.26k
    if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
7389
152
        if (!g.ActiveIdNoClearOnFocusLoss && !active_id_window_is_dock_node_host)
7390
93
            ClearActiveID();
7391
7392
    // Passing NULL allow to disable keyboard focus
7393
7.26k
    if (!window)
7394
5.88k
        return;
7395
1.37k
    window->LastFrameJustFocused = g.FrameCount;
7396
7397
    // Select in dock node
7398
1.37k
    if (dock_node && dock_node->TabBar)
7399
0
        dock_node->TabBar->SelectedTabId = dock_node->TabBar->NextSelectedTabId = window->TabId;
7400
7401
    // Bring to front
7402
1.37k
    BringWindowToFocusFront(focus_front_window);
7403
1.37k
    if (((window->Flags | focus_front_window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
7404
1.37k
        BringWindowToDisplayFront(display_front_window);
7405
1.37k
}
7406
7407
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
7408
0
{
7409
0
    ImGuiContext& g = *GImGui;
7410
0
    int start_idx = g.WindowsFocusOrder.Size - 1;
7411
0
    if (under_this_window != NULL)
7412
0
    {
7413
        // Aim at root window behind us, if we are in a child window that's our own root (see #4640)
7414
0
        int offset = -1;
7415
0
        while (under_this_window->Flags & ImGuiWindowFlags_ChildWindow)
7416
0
        {
7417
0
            under_this_window = under_this_window->ParentWindow;
7418
0
            offset = 0;
7419
0
        }
7420
0
        start_idx = FindWindowFocusIndex(under_this_window) + offset;
7421
0
    }
7422
0
    for (int i = start_idx; i >= 0; i--)
7423
0
    {
7424
        // We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
7425
0
        ImGuiWindow* window = g.WindowsFocusOrder[i];
7426
0
        IM_ASSERT(window == window->RootWindow);
7427
0
        if (window != ignore_window && window->WasActive)
7428
0
            if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
7429
0
            {
7430
                // FIXME-DOCK: This is failing (lagging by one frame) for docked windows.
7431
                // If A and B are docked into window and B disappear, at the NewFrame() call site window->NavLastChildNavWindow will still point to B.
7432
                // We might leverage the tab order implicitly stored in window->DockNodeAsHost->TabBar (essentially the 'most_recently_selected_tab' code in tab bar will do that but on next update)
7433
                // to tell which is the "previous" window. Or we may leverage 'LastFrameFocused/LastFrameJustFocused' and have this function handle child window itself?
7434
0
                ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
7435
0
                FocusWindow(focus_window);
7436
0
                return;
7437
0
            }
7438
0
    }
7439
0
    FocusWindow(NULL);
7440
0
}
7441
7442
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
7443
void ImGui::SetCurrentFont(ImFont* font)
7444
34.4k
{
7445
34.4k
    ImGuiContext& g = *GImGui;
7446
34.4k
    IM_ASSERT(font && font->IsLoaded());    // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
7447
34.4k
    IM_ASSERT(font->Scale > 0.0f);
7448
34.4k
    g.Font = font;
7449
34.4k
    g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
7450
34.4k
    g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
7451
7452
34.4k
    ImFontAtlas* atlas = g.Font->ContainerAtlas;
7453
34.4k
    g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
7454
34.4k
    g.DrawListSharedData.TexUvLines = atlas->TexUvLines;
7455
34.4k
    g.DrawListSharedData.Font = g.Font;
7456
34.4k
    g.DrawListSharedData.FontSize = g.FontSize;
7457
34.4k
}
7458
7459
void ImGui::PushFont(ImFont* font)
7460
0
{
7461
0
    ImGuiContext& g = *GImGui;
7462
0
    if (!font)
7463
0
        font = GetDefaultFont();
7464
0
    SetCurrentFont(font);
7465
0
    g.FontStack.push_back(font);
7466
0
    g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
7467
0
}
7468
7469
void  ImGui::PopFont()
7470
0
{
7471
0
    ImGuiContext& g = *GImGui;
7472
0
    g.CurrentWindow->DrawList->PopTextureID();
7473
0
    g.FontStack.pop_back();
7474
0
    SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
7475
0
}
7476
7477
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
7478
3.02k
{
7479
3.02k
    ImGuiContext& g = *GImGui;
7480
3.02k
    ImGuiItemFlags item_flags = g.CurrentItemFlags;
7481
3.02k
    IM_ASSERT(item_flags == g.ItemFlagsStack.back());
7482
3.02k
    if (enabled)
7483
0
        item_flags |= option;
7484
3.02k
    else
7485
3.02k
        item_flags &= ~option;
7486
3.02k
    g.CurrentItemFlags = item_flags;
7487
3.02k
    g.ItemFlagsStack.push_back(item_flags);
7488
3.02k
}
7489
7490
void ImGui::PopItemFlag()
7491
3.02k
{
7492
3.02k
    ImGuiContext& g = *GImGui;
7493
3.02k
    IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
7494
3.02k
    g.ItemFlagsStack.pop_back();
7495
3.02k
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7496
3.02k
}
7497
7498
// BeginDisabled()/EndDisabled()
7499
// - Those can be nested but it cannot be used to enable an already disabled section (a single BeginDisabled(true) in the stack is enough to keep everything disabled)
7500
// - Visually this is currently altering alpha, but it is expected that in a future styling system this would work differently.
7501
// - Feedback welcome at https://github.com/ocornut/imgui/issues/211
7502
// - BeginDisabled(false) essentially does nothing useful but is provided to facilitate use of boolean expressions. If you can avoid calling BeginDisabled(False)/EndDisabled() best to avoid it.
7503
// - Optimized shortcuts instead of PushStyleVar() + PushItemFlag()
7504
void ImGui::BeginDisabled(bool disabled)
7505
0
{
7506
0
    ImGuiContext& g = *GImGui;
7507
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7508
0
    if (!was_disabled && disabled)
7509
0
    {
7510
0
        g.DisabledAlphaBackup = g.Style.Alpha;
7511
0
        g.Style.Alpha *= g.Style.DisabledAlpha; // PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * g.Style.DisabledAlpha);
7512
0
    }
7513
0
    if (was_disabled || disabled)
7514
0
        g.CurrentItemFlags |= ImGuiItemFlags_Disabled;
7515
0
    g.ItemFlagsStack.push_back(g.CurrentItemFlags);
7516
0
    g.DisabledStackSize++;
7517
0
}
7518
7519
void ImGui::EndDisabled()
7520
0
{
7521
0
    ImGuiContext& g = *GImGui;
7522
0
    IM_ASSERT(g.DisabledStackSize > 0);
7523
0
    g.DisabledStackSize--;
7524
0
    bool was_disabled = (g.CurrentItemFlags & ImGuiItemFlags_Disabled) != 0;
7525
    //PopItemFlag();
7526
0
    g.ItemFlagsStack.pop_back();
7527
0
    g.CurrentItemFlags = g.ItemFlagsStack.back();
7528
0
    if (was_disabled && (g.CurrentItemFlags & ImGuiItemFlags_Disabled) == 0)
7529
0
        g.Style.Alpha = g.DisabledAlphaBackup; //PopStyleVar();
7530
0
}
7531
7532
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
7533
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
7534
3.02k
{
7535
3.02k
    PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
7536
3.02k
}
7537
7538
void ImGui::PopAllowKeyboardFocus()
7539
3.02k
{
7540
3.02k
    PopItemFlag();
7541
3.02k
}
7542
7543
void ImGui::PushButtonRepeat(bool repeat)
7544
0
{
7545
0
    PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
7546
0
}
7547
7548
void ImGui::PopButtonRepeat()
7549
0
{
7550
0
    PopItemFlag();
7551
0
}
7552
7553
void ImGui::PushTextWrapPos(float wrap_pos_x)
7554
0
{
7555
0
    ImGuiWindow* window = GetCurrentWindow();
7556
0
    window->DC.TextWrapPosStack.push_back(window->DC.TextWrapPos);
7557
0
    window->DC.TextWrapPos = wrap_pos_x;
7558
0
}
7559
7560
void ImGui::PopTextWrapPos()
7561
0
{
7562
0
    ImGuiWindow* window = GetCurrentWindow();
7563
0
    window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
7564
0
    window->DC.TextWrapPosStack.pop_back();
7565
0
}
7566
7567
static ImGuiWindow* GetCombinedRootWindow(ImGuiWindow* window, bool popup_hierarchy, bool dock_hierarchy)
7568
0
{
7569
0
    ImGuiWindow* last_window = NULL;
7570
0
    while (last_window != window)
7571
0
    {
7572
0
        last_window = window;
7573
0
        window = window->RootWindow;
7574
0
        if (popup_hierarchy)
7575
0
            window = window->RootWindowPopupTree;
7576
0
    if (dock_hierarchy)
7577
0
      window = window->RootWindowDockTree;
7578
0
  }
7579
0
    return window;
7580
0
}
7581
7582
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent, bool popup_hierarchy, bool dock_hierarchy)
7583
0
{
7584
0
    ImGuiWindow* window_root = GetCombinedRootWindow(window, popup_hierarchy, dock_hierarchy);
7585
0
    if (window_root == potential_parent)
7586
0
        return true;
7587
0
    while (window != NULL)
7588
0
    {
7589
0
        if (window == potential_parent)
7590
0
            return true;
7591
0
        if (window == window_root) // end of chain
7592
0
            return false;
7593
0
        window = window->ParentWindow;
7594
0
    }
7595
0
    return false;
7596
0
}
7597
7598
bool ImGui::IsWindowWithinBeginStackOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
7599
0
{
7600
0
    if (window->RootWindow == potential_parent)
7601
0
        return true;
7602
0
    while (window != NULL)
7603
0
    {
7604
0
        if (window == potential_parent)
7605
0
            return true;
7606
0
        window = window->ParentWindowInBeginStack;
7607
0
    }
7608
0
    return false;
7609
0
}
7610
7611
bool ImGui::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
7612
0
{
7613
0
    ImGuiContext& g = *GImGui;
7614
7615
    // It would be saner to ensure that display layer is always reflected in the g.Windows[] order, which would likely requires altering all manipulations of that array
7616
0
    const int display_layer_delta = GetWindowDisplayLayer(potential_above) - GetWindowDisplayLayer(potential_below);
7617
0
    if (display_layer_delta != 0)
7618
0
        return display_layer_delta > 0;
7619
7620
0
    for (int i = g.Windows.Size - 1; i >= 0; i--)
7621
0
    {
7622
0
        ImGuiWindow* candidate_window = g.Windows[i];
7623
0
        if (candidate_window == potential_above)
7624
0
            return true;
7625
0
        if (candidate_window == potential_below)
7626
0
            return false;
7627
0
    }
7628
0
    return false;
7629
0
}
7630
7631
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
7632
3.91k
{
7633
3.91k
    IM_ASSERT((flags & (ImGuiHoveredFlags_AllowWhenOverlapped | ImGuiHoveredFlags_AllowWhenDisabled)) == 0);   // Flags not supported by this function
7634
3.91k
    ImGuiContext& g = *GImGui;
7635
3.91k
    ImGuiWindow* ref_window = g.HoveredWindow;
7636
3.91k
    ImGuiWindow* cur_window = g.CurrentWindow;
7637
3.91k
    if (ref_window == NULL)
7638
3.22k
        return false;
7639
7640
688
    if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
7641
688
    {
7642
688
        IM_ASSERT(cur_window); // Not inside a Begin()/End()
7643
688
        const bool popup_hierarchy = (flags & ImGuiHoveredFlags_NoPopupHierarchy) == 0;
7644
688
        const bool dock_hierarchy = (flags & ImGuiHoveredFlags_DockHierarchy) != 0;
7645
688
        if (flags & ImGuiHoveredFlags_RootWindow)
7646
0
            cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7647
7648
688
        bool result;
7649
688
        if (flags & ImGuiHoveredFlags_ChildWindows)
7650
0
            result = IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7651
688
        else
7652
688
            result = (ref_window == cur_window);
7653
688
        if (!result)
7654
524
            return false;
7655
688
    }
7656
7657
164
    if (!IsWindowContentHoverable(ref_window, flags))
7658
0
        return false;
7659
164
    if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
7660
164
        if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != ref_window->MoveId)
7661
91
            return false;
7662
73
    return true;
7663
164
}
7664
7665
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
7666
5.97k
{
7667
5.97k
    ImGuiContext& g = *GImGui;
7668
5.97k
    ImGuiWindow* ref_window = g.NavWindow;
7669
5.97k
    ImGuiWindow* cur_window = g.CurrentWindow;
7670
7671
5.97k
    if (ref_window == NULL)
7672
3.46k
        return false;
7673
2.51k
    if (flags & ImGuiFocusedFlags_AnyWindow)
7674
0
        return true;
7675
7676
2.51k
    IM_ASSERT(cur_window); // Not inside a Begin()/End()
7677
2.51k
    const bool popup_hierarchy = (flags & ImGuiFocusedFlags_NoPopupHierarchy) == 0;
7678
2.51k
    const bool dock_hierarchy = (flags & ImGuiFocusedFlags_DockHierarchy) != 0;
7679
2.51k
    if (flags & ImGuiHoveredFlags_RootWindow)
7680
0
        cur_window = GetCombinedRootWindow(cur_window, popup_hierarchy, dock_hierarchy);
7681
7682
2.51k
    if (flags & ImGuiHoveredFlags_ChildWindows)
7683
0
        return IsWindowChildOf(ref_window, cur_window, popup_hierarchy, dock_hierarchy);
7684
2.51k
    else
7685
2.51k
        return (ref_window == cur_window);
7686
2.51k
}
7687
7688
ImGuiID ImGui::GetWindowDockID()
7689
0
{
7690
0
    ImGuiContext& g = *GImGui;
7691
0
    return g.CurrentWindow->DockId;
7692
0
}
7693
7694
bool ImGui::IsWindowDocked()
7695
0
{
7696
0
    ImGuiContext& g = *GImGui;
7697
0
    return g.CurrentWindow->DockIsActive;
7698
0
}
7699
7700
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
7701
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
7702
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
7703
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
7704
0
{
7705
0
    return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
7706
0
}
7707
7708
float ImGui::GetWindowWidth()
7709
1.03k
{
7710
1.03k
    ImGuiWindow* window = GImGui->CurrentWindow;
7711
1.03k
    return window->Size.x;
7712
1.03k
}
7713
7714
float ImGui::GetWindowHeight()
7715
1.03k
{
7716
1.03k
    ImGuiWindow* window = GImGui->CurrentWindow;
7717
1.03k
    return window->Size.y;
7718
1.03k
}
7719
7720
ImVec2 ImGui::GetWindowPos()
7721
0
{
7722
0
    ImGuiContext& g = *GImGui;
7723
0
    ImGuiWindow* window = g.CurrentWindow;
7724
0
    return window->Pos;
7725
0
}
7726
7727
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
7728
66
{
7729
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7730
66
    if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
7731
0
        return;
7732
7733
66
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7734
66
    window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7735
66
    window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
7736
7737
    // Set
7738
66
    const ImVec2 old_pos = window->Pos;
7739
66
    window->Pos = ImFloor(pos);
7740
66
    ImVec2 offset = window->Pos - old_pos;
7741
66
    if (offset.x == 0.0f && offset.y == 0.0f)
7742
0
        return;
7743
66
    MarkIniSettingsDirty(window);
7744
    // FIXME: share code with TranslateWindow(), need to confirm whether the 3 rect modified by TranslateWindow() are desirable here.
7745
66
    window->DC.CursorPos += offset;         // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
7746
66
    window->DC.CursorMaxPos += offset;      // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
7747
66
    window->DC.IdealMaxPos += offset;
7748
66
    window->DC.CursorStartPos += offset;
7749
66
}
7750
7751
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
7752
0
{
7753
0
    ImGuiWindow* window = GetCurrentWindowRead();
7754
0
    SetWindowPos(window, pos, cond);
7755
0
}
7756
7757
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
7758
0
{
7759
0
    if (ImGuiWindow* window = FindWindowByName(name))
7760
0
        SetWindowPos(window, pos, cond);
7761
0
}
7762
7763
ImVec2 ImGui::GetWindowSize()
7764
0
{
7765
0
    ImGuiWindow* window = GetCurrentWindowRead();
7766
0
    return window->Size;
7767
0
}
7768
7769
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
7770
37.4k
{
7771
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7772
37.4k
    if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
7773
34.4k
        return;
7774
7775
3.02k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7776
3.02k
    window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7777
7778
    // Set
7779
3.02k
    ImVec2 old_size = window->SizeFull;
7780
3.02k
    window->AutoFitFramesX = (size.x <= 0.0f) ? 2 : 0;
7781
3.02k
    window->AutoFitFramesY = (size.y <= 0.0f) ? 2 : 0;
7782
3.02k
    if (size.x <= 0.0f)
7783
0
        window->AutoFitOnlyGrows = false;
7784
3.02k
    else
7785
3.02k
        window->SizeFull.x = IM_FLOOR(size.x);
7786
3.02k
    if (size.y <= 0.0f)
7787
0
        window->AutoFitOnlyGrows = false;
7788
3.02k
    else
7789
3.02k
        window->SizeFull.y = IM_FLOOR(size.y);
7790
3.02k
    if (old_size.x != window->SizeFull.x || old_size.y != window->SizeFull.y)
7791
992
        MarkIniSettingsDirty(window);
7792
3.02k
}
7793
7794
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
7795
0
{
7796
0
    SetWindowSize(GImGui->CurrentWindow, size, cond);
7797
0
}
7798
7799
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
7800
0
{
7801
0
    if (ImGuiWindow* window = FindWindowByName(name))
7802
0
        SetWindowSize(window, size, cond);
7803
0
}
7804
7805
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
7806
0
{
7807
    // Test condition (NB: bit 0 is always true) and clear flags for next time
7808
0
    if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
7809
0
        return;
7810
0
    window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
7811
7812
    // Set
7813
0
    window->Collapsed = collapsed;
7814
0
}
7815
7816
void ImGui::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
7817
0
{
7818
0
    IM_ASSERT(window->HitTestHoleSize.x == 0);     // We don't support multiple holes/hit test filters
7819
0
    window->HitTestHoleSize = ImVec2ih(size);
7820
0
    window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
7821
0
}
7822
7823
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
7824
0
{
7825
0
    SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
7826
0
}
7827
7828
bool ImGui::IsWindowCollapsed()
7829
0
{
7830
0
    ImGuiWindow* window = GetCurrentWindowRead();
7831
0
    return window->Collapsed;
7832
0
}
7833
7834
bool ImGui::IsWindowAppearing()
7835
0
{
7836
0
    ImGuiWindow* window = GetCurrentWindowRead();
7837
0
    return window->Appearing;
7838
0
}
7839
7840
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
7841
0
{
7842
0
    if (ImGuiWindow* window = FindWindowByName(name))
7843
0
        SetWindowCollapsed(window, collapsed, cond);
7844
0
}
7845
7846
void ImGui::SetWindowFocus()
7847
1.03k
{
7848
1.03k
    FocusWindow(GImGui->CurrentWindow);
7849
1.03k
}
7850
7851
void ImGui::SetWindowFocus(const char* name)
7852
0
{
7853
0
    if (name)
7854
0
    {
7855
0
        if (ImGuiWindow* window = FindWindowByName(name))
7856
0
            FocusWindow(window);
7857
0
    }
7858
0
    else
7859
0
    {
7860
0
        FocusWindow(NULL);
7861
0
    }
7862
0
}
7863
7864
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
7865
0
{
7866
0
    ImGuiContext& g = *GImGui;
7867
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7868
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
7869
0
    g.NextWindowData.PosVal = pos;
7870
0
    g.NextWindowData.PosPivotVal = pivot;
7871
0
    g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
7872
0
    g.NextWindowData.PosUndock = true;
7873
0
}
7874
7875
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
7876
37.4k
{
7877
37.4k
    ImGuiContext& g = *GImGui;
7878
37.4k
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7879
37.4k
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
7880
37.4k
    g.NextWindowData.SizeVal = size;
7881
37.4k
    g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
7882
37.4k
}
7883
7884
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
7885
0
{
7886
0
    ImGuiContext& g = *GImGui;
7887
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
7888
0
    g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
7889
0
    g.NextWindowData.SizeCallback = custom_callback;
7890
0
    g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
7891
0
}
7892
7893
// Content size = inner scrollable rectangle, padded with WindowPadding.
7894
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
7895
void ImGui::SetNextWindowContentSize(const ImVec2& size)
7896
0
{
7897
0
    ImGuiContext& g = *GImGui;
7898
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
7899
0
    g.NextWindowData.ContentSizeVal = ImFloor(size);
7900
0
}
7901
7902
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
7903
0
{
7904
0
    ImGuiContext& g = *GImGui;
7905
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
7906
0
    g.NextWindowData.ScrollVal = scroll;
7907
0
}
7908
7909
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
7910
0
{
7911
0
    ImGuiContext& g = *GImGui;
7912
0
    IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
7913
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
7914
0
    g.NextWindowData.CollapsedVal = collapsed;
7915
0
    g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
7916
0
}
7917
7918
void ImGui::SetNextWindowFocus()
7919
0
{
7920
0
    ImGuiContext& g = *GImGui;
7921
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
7922
0
}
7923
7924
void ImGui::SetNextWindowBgAlpha(float alpha)
7925
0
{
7926
0
    ImGuiContext& g = *GImGui;
7927
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
7928
0
    g.NextWindowData.BgAlphaVal = alpha;
7929
0
}
7930
7931
void ImGui::SetNextWindowViewport(ImGuiID id)
7932
0
{
7933
0
    ImGuiContext& g = *GImGui;
7934
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasViewport;
7935
0
    g.NextWindowData.ViewportId = id;
7936
0
}
7937
7938
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
7939
0
{
7940
0
    ImGuiContext& g = *GImGui;
7941
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasDock;
7942
0
    g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
7943
0
    g.NextWindowData.DockId = id;
7944
0
}
7945
7946
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
7947
0
{
7948
0
    ImGuiContext& g = *GImGui;
7949
0
    IM_ASSERT((window_class->ViewportFlagsOverrideSet & window_class->ViewportFlagsOverrideClear) == 0); // Cannot set both set and clear for the same bit
7950
0
    g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasWindowClass;
7951
0
    g.NextWindowData.WindowClass = *window_class;
7952
0
}
7953
7954
ImDrawList* ImGui::GetWindowDrawList()
7955
3.02k
{
7956
3.02k
    ImGuiWindow* window = GetCurrentWindow();
7957
3.02k
    return window->DrawList;
7958
3.02k
}
7959
7960
float ImGui::GetWindowDpiScale()
7961
0
{
7962
0
    ImGuiContext& g = *GImGui;
7963
0
    return g.CurrentDpiScale;
7964
0
}
7965
7966
ImGuiViewport* ImGui::GetWindowViewport()
7967
0
{
7968
0
    ImGuiContext& g = *GImGui;
7969
0
    IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
7970
0
    return g.CurrentViewport;
7971
0
}
7972
7973
ImFont* ImGui::GetFont()
7974
37.1k
{
7975
37.1k
    return GImGui->Font;
7976
37.1k
}
7977
7978
float ImGui::GetFontSize()
7979
37.1k
{
7980
37.1k
    return GImGui->FontSize;
7981
37.1k
}
7982
7983
ImVec2 ImGui::GetFontTexUvWhitePixel()
7984
0
{
7985
0
    return GImGui->DrawListSharedData.TexUvWhitePixel;
7986
0
}
7987
7988
void ImGui::SetWindowFontScale(float scale)
7989
0
{
7990
0
    IM_ASSERT(scale > 0.0f);
7991
0
    ImGuiContext& g = *GImGui;
7992
0
    ImGuiWindow* window = GetCurrentWindow();
7993
0
    window->FontWindowScale = scale;
7994
0
    g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
7995
0
}
7996
7997
void ImGui::ActivateItem(ImGuiID id)
7998
0
{
7999
0
    ImGuiContext& g = *GImGui;
8000
0
    g.NavNextActivateId = id;
8001
0
    g.NavNextActivateFlags = ImGuiActivateFlags_None;
8002
0
}
8003
8004
void ImGui::PushFocusScope(ImGuiID id)
8005
71.9k
{
8006
71.9k
    ImGuiContext& g = *GImGui;
8007
71.9k
    g.FocusScopeStack.push_back(id);
8008
71.9k
    g.CurrentFocusScopeId = id;
8009
71.9k
}
8010
8011
void ImGui::PopFocusScope()
8012
71.9k
{
8013
71.9k
    ImGuiContext& g = *GImGui;
8014
71.9k
    IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
8015
71.9k
    g.FocusScopeStack.pop_back();
8016
71.9k
    g.CurrentFocusScopeId = g.FocusScopeStack.Size ? g.FocusScopeStack.back() : 0;
8017
71.9k
}
8018
8019
// Note: this will likely be called ActivateItem() once we rework our Focus/Activation system!
8020
void ImGui::SetKeyboardFocusHere(int offset)
8021
0
{
8022
0
    ImGuiContext& g = *GImGui;
8023
0
    ImGuiWindow* window = g.CurrentWindow;
8024
0
    IM_ASSERT(offset >= -1);    // -1 is allowed but not below
8025
0
    IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere(%d) in window \"%s\"\n", offset, window->Name);
8026
8027
    // It makes sense in the vast majority of cases to never interrupt a drag and drop.
8028
    // When we refactor this function into ActivateItem() we may want to make this an option.
8029
    // MovingWindow is protected from most user inputs using SetActiveIdUsingNavAndKeys(), but
8030
    // is also automatically dropped in the event g.ActiveId is stolen.
8031
0
    if (g.DragDropActive || g.MovingWindow != NULL)
8032
0
    {
8033
0
        IMGUI_DEBUG_LOG_ACTIVEID("SetKeyboardFocusHere() ignored while DragDropActive!\n");
8034
0
        return;
8035
0
    }
8036
8037
0
    SetNavWindow(window);
8038
8039
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
8040
0
    NavMoveRequestSubmit(ImGuiDir_None, offset < 0 ? ImGuiDir_Up : ImGuiDir_Down, ImGuiNavMoveFlags_Tabbing | ImGuiNavMoveFlags_FocusApi, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
8041
0
    if (offset == -1)
8042
0
    {
8043
0
        NavMoveRequestResolveWithLastItem(&g.NavMoveResultLocal);
8044
0
    }
8045
0
    else
8046
0
    {
8047
0
        g.NavTabbingDir = 1;
8048
0
        g.NavTabbingCounter = offset + 1;
8049
0
    }
8050
0
}
8051
8052
void ImGui::SetItemDefaultFocus()
8053
0
{
8054
0
    ImGuiContext& g = *GImGui;
8055
0
    ImGuiWindow* window = g.CurrentWindow;
8056
0
    if (!window->Appearing)
8057
0
        return;
8058
0
    if (g.NavWindow != window->RootWindowForNav || (!g.NavInitRequest && g.NavInitResultId == 0) || g.NavLayer != window->DC.NavLayerCurrent)
8059
0
        return;
8060
8061
0
    g.NavInitRequest = false;
8062
0
    g.NavInitResultId = g.LastItemData.ID;
8063
0
    g.NavInitResultRectRel = WindowRectAbsToRel(window, g.LastItemData.Rect);
8064
0
    NavUpdateAnyRequestFlag();
8065
8066
    // Scroll could be done in NavInitRequestApplyResult() via an opt-in flag (we however don't want regular init requests to scroll)
8067
0
    if (!IsItemVisible())
8068
0
        ScrollToRectEx(window, g.LastItemData.Rect, ImGuiScrollFlags_None);
8069
0
}
8070
8071
void ImGui::SetStateStorage(ImGuiStorage* tree)
8072
0
{
8073
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8074
0
    window->DC.StateStorage = tree ? tree : &window->StateStorage;
8075
0
}
8076
8077
ImGuiStorage* ImGui::GetStateStorage()
8078
0
{
8079
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8080
0
    return window->DC.StateStorage;
8081
0
}
8082
8083
void ImGui::PushID(const char* str_id)
8084
3.02k
{
8085
3.02k
    ImGuiContext& g = *GImGui;
8086
3.02k
    ImGuiWindow* window = g.CurrentWindow;
8087
3.02k
    ImGuiID id = window->GetID(str_id);
8088
3.02k
    window->IDStack.push_back(id);
8089
3.02k
}
8090
8091
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
8092
0
{
8093
0
    ImGuiContext& g = *GImGui;
8094
0
    ImGuiWindow* window = g.CurrentWindow;
8095
0
    ImGuiID id = window->GetID(str_id_begin, str_id_end);
8096
0
    window->IDStack.push_back(id);
8097
0
}
8098
8099
void ImGui::PushID(const void* ptr_id)
8100
0
{
8101
0
    ImGuiContext& g = *GImGui;
8102
0
    ImGuiWindow* window = g.CurrentWindow;
8103
0
    ImGuiID id = window->GetID(ptr_id);
8104
0
    window->IDStack.push_back(id);
8105
0
}
8106
8107
void ImGui::PushID(int int_id)
8108
0
{
8109
0
    ImGuiContext& g = *GImGui;
8110
0
    ImGuiWindow* window = g.CurrentWindow;
8111
0
    ImGuiID id = window->GetID(int_id);
8112
0
    window->IDStack.push_back(id);
8113
0
}
8114
8115
// Push a given id value ignoring the ID stack as a seed.
8116
void ImGui::PushOverrideID(ImGuiID id)
8117
0
{
8118
0
    ImGuiContext& g = *GImGui;
8119
0
    ImGuiWindow* window = g.CurrentWindow;
8120
0
    if (g.DebugHookIdInfo == id)
8121
0
        DebugHookIdInfo(id, ImGuiDataType_ID, NULL, NULL);
8122
0
    window->IDStack.push_back(id);
8123
0
}
8124
8125
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
8126
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
8127
//  for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
8128
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
8129
0
{
8130
0
    ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
8131
0
    ImGuiContext& g = *GImGui;
8132
0
    if (g.DebugHookIdInfo == id)
8133
0
        DebugHookIdInfo(id, ImGuiDataType_String, str, str_end);
8134
0
    return id;
8135
0
}
8136
8137
ImGuiID ImGui::GetIDWithSeed(int n, ImGuiID seed)
8138
0
{
8139
0
    ImGuiID id = ImHashData(&n, sizeof(n), seed);
8140
0
    ImGuiContext& g = *GImGui;
8141
0
    if (g.DebugHookIdInfo == id)
8142
0
        DebugHookIdInfo(id, ImGuiDataType_S32, (void*)(intptr_t)n, NULL);
8143
0
    return id;
8144
0
}
8145
8146
void ImGui::PopID()
8147
3.02k
{
8148
3.02k
    ImGuiWindow* window = GImGui->CurrentWindow;
8149
3.02k
    IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
8150
3.02k
    window->IDStack.pop_back();
8151
3.02k
}
8152
8153
ImGuiID ImGui::GetID(const char* str_id)
8154
0
{
8155
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8156
0
    return window->GetID(str_id);
8157
0
}
8158
8159
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
8160
0
{
8161
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8162
0
    return window->GetID(str_id_begin, str_id_end);
8163
0
}
8164
8165
ImGuiID ImGui::GetID(const void* ptr_id)
8166
0
{
8167
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8168
0
    return window->GetID(ptr_id);
8169
0
}
8170
8171
bool ImGui::IsRectVisible(const ImVec2& size)
8172
0
{
8173
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8174
0
    return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
8175
0
}
8176
8177
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
8178
0
{
8179
0
    ImGuiWindow* window = GImGui->CurrentWindow;
8180
0
    return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
8181
0
}
8182
8183
8184
//-----------------------------------------------------------------------------
8185
// [SECTION] INPUTS
8186
//-----------------------------------------------------------------------------
8187
// - GetKeyData() [Internal]
8188
// - GetKeyIndex() [Internal]
8189
// - GetKeyName()
8190
// - GetKeyChordName() [Internal]
8191
// - CalcTypematicRepeatAmount() [Internal]
8192
// - GetTypematicRepeatRate() [Internal]
8193
// - GetKeyPressedAmount() [Internal]
8194
// - GetKeyMagnitude2d() [Internal]
8195
//-----------------------------------------------------------------------------
8196
// - UpdateKeyRoutingTable() [Internal]
8197
// - GetRoutingIdFromOwnerId() [Internal]
8198
// - GetShortcutRoutingData() [Internal]
8199
// - CalcRoutingScore() [Internal]
8200
// - SetShortcutRouting() [Internal]
8201
// - TestShortcutRouting() [Internal]
8202
//-----------------------------------------------------------------------------
8203
// - IsKeyDown()
8204
// - IsKeyPressed()
8205
// - IsKeyReleased()
8206
//-----------------------------------------------------------------------------
8207
// - IsMouseDown()
8208
// - IsMouseClicked()
8209
// - IsMouseReleased()
8210
// - IsMouseDoubleClicked()
8211
// - GetMouseClickedCount()
8212
// - IsMouseHoveringRect() [Internal]
8213
// - IsMouseDragPastThreshold() [Internal]
8214
// - IsMouseDragging()
8215
// - GetMousePos()
8216
// - GetMousePosOnOpeningCurrentPopup()
8217
// - IsMousePosValid()
8218
// - IsAnyMouseDown()
8219
// - GetMouseDragDelta()
8220
// - ResetMouseDragDelta()
8221
// - GetMouseCursor()
8222
// - SetMouseCursor()
8223
//-----------------------------------------------------------------------------
8224
// - UpdateAliasKey()
8225
// - GetMergedModsFromKeys()
8226
// - UpdateKeyboardInputs()
8227
// - UpdateMouseInputs()
8228
//-----------------------------------------------------------------------------
8229
// - LockWheelingWindow [Internal]
8230
// - FindBestWheelingWindow [Internal]
8231
// - UpdateMouseWheel() [Internal]
8232
//-----------------------------------------------------------------------------
8233
// - SetNextFrameWantCaptureKeyboard()
8234
// - SetNextFrameWantCaptureMouse()
8235
//-----------------------------------------------------------------------------
8236
// - GetInputSourceName() [Internal]
8237
// - DebugPrintInputEvent() [Internal]
8238
// - UpdateInputEvents() [Internal]
8239
//-----------------------------------------------------------------------------
8240
// - GetKeyOwner() [Internal]
8241
// - TestKeyOwner() [Internal]
8242
// - SetKeyOwner() [Internal]
8243
// - SetItemKeyOwner() [Internal]
8244
// - Shortcut() [Internal]
8245
//-----------------------------------------------------------------------------
8246
8247
ImGuiKeyData* ImGui::GetKeyData(ImGuiKey key)
8248
853k
{
8249
853k
    ImGuiContext& g = *GImGui;
8250
8251
    // Special storage location for mods
8252
853k
    if (key & ImGuiMod_Mask_)
8253
310k
        key = ConvertSingleModFlagToKey(key);
8254
8255
853k
    int index;
8256
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8257
    IM_ASSERT(key >= ImGuiKey_LegacyNativeKey_BEGIN && key < ImGuiKey_NamedKey_END);
8258
    if (IsLegacyKey(key))
8259
        index = (g.IO.KeyMap[key] != -1) ? g.IO.KeyMap[key] : key; // Remap native->imgui or imgui->native
8260
    else
8261
        index = key;
8262
#else
8263
853k
    IM_ASSERT(IsNamedKey(key) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend & user code.");
8264
853k
    index = key - ImGuiKey_NamedKey_BEGIN;
8265
853k
#endif
8266
853k
    return &g.IO.KeysData[index];
8267
853k
}
8268
8269
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8270
ImGuiKey ImGui::GetKeyIndex(ImGuiKey key)
8271
{
8272
    ImGuiContext& g = *GImGui;
8273
    IM_ASSERT(IsNamedKey(key));
8274
    const ImGuiKeyData* key_data = GetKeyData(key);
8275
    return (ImGuiKey)(key_data - g.IO.KeysData);
8276
}
8277
#endif
8278
8279
// Those names a provided for debugging purpose and are not meant to be saved persistently not compared.
8280
static const char* const GKeyNames[] =
8281
{
8282
    "Tab", "LeftArrow", "RightArrow", "UpArrow", "DownArrow", "PageUp", "PageDown",
8283
    "Home", "End", "Insert", "Delete", "Backspace", "Space", "Enter", "Escape",
8284
    "LeftCtrl", "LeftShift", "LeftAlt", "LeftSuper", "RightCtrl", "RightShift", "RightAlt", "RightSuper", "Menu",
8285
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
8286
    "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
8287
    "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12",
8288
    "Apostrophe", "Comma", "Minus", "Period", "Slash", "Semicolon", "Equal", "LeftBracket",
8289
    "Backslash", "RightBracket", "GraveAccent", "CapsLock", "ScrollLock", "NumLock", "PrintScreen",
8290
    "Pause", "Keypad0", "Keypad1", "Keypad2", "Keypad3", "Keypad4", "Keypad5", "Keypad6",
8291
    "Keypad7", "Keypad8", "Keypad9", "KeypadDecimal", "KeypadDivide", "KeypadMultiply",
8292
    "KeypadSubtract", "KeypadAdd", "KeypadEnter", "KeypadEqual",
8293
    "GamepadStart", "GamepadBack",
8294
    "GamepadFaceLeft", "GamepadFaceRight", "GamepadFaceUp", "GamepadFaceDown",
8295
    "GamepadDpadLeft", "GamepadDpadRight", "GamepadDpadUp", "GamepadDpadDown",
8296
    "GamepadL1", "GamepadR1", "GamepadL2", "GamepadR2", "GamepadL3", "GamepadR3",
8297
    "GamepadLStickLeft", "GamepadLStickRight", "GamepadLStickUp", "GamepadLStickDown",
8298
    "GamepadRStickLeft", "GamepadRStickRight", "GamepadRStickUp", "GamepadRStickDown",
8299
    "MouseLeft", "MouseRight", "MouseMiddle", "MouseX1", "MouseX2", "MouseWheelX", "MouseWheelY",
8300
    "ModCtrl", "ModShift", "ModAlt", "ModSuper", // ReservedForModXXX are showing the ModXXX names.
8301
};
8302
IM_STATIC_ASSERT(ImGuiKey_NamedKey_COUNT == IM_ARRAYSIZE(GKeyNames));
8303
8304
const char* ImGui::GetKeyName(ImGuiKey key)
8305
0
{
8306
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
8307
0
    IM_ASSERT((IsNamedKey(key) || key == ImGuiKey_None) && "Support for user key indices was dropped in favor of ImGuiKey. Please update backend and user code.");
8308
#else
8309
    if (IsLegacyKey(key))
8310
    {
8311
        ImGuiIO& io = GetIO();
8312
        if (io.KeyMap[key] == -1)
8313
            return "N/A";
8314
        IM_ASSERT(IsNamedKey((ImGuiKey)io.KeyMap[key]));
8315
        key = (ImGuiKey)io.KeyMap[key];
8316
    }
8317
#endif
8318
0
    if (key == ImGuiKey_None)
8319
0
        return "None";
8320
0
    if (key & ImGuiMod_Mask_)
8321
0
        key = ConvertSingleModFlagToKey(key);
8322
0
    if (!IsNamedKey(key))
8323
0
        return "Unknown";
8324
8325
0
    return GKeyNames[key - ImGuiKey_NamedKey_BEGIN];
8326
0
}
8327
8328
// ImGuiMod_Shortcut is translated to either Ctrl or Super.
8329
void ImGui::GetKeyChordName(ImGuiKeyChord key_chord, char* out_buf, int out_buf_size)
8330
0
{
8331
0
    ImGuiContext& g = *GImGui;
8332
0
    if (key_chord & ImGuiMod_Shortcut)
8333
0
        key_chord = ConvertShortcutMod(key_chord);
8334
0
    ImFormatString(out_buf, (size_t)out_buf_size, "%s%s%s%s%s",
8335
0
        (key_chord & ImGuiMod_Ctrl) ? "Ctrl+" : "",
8336
0
        (key_chord & ImGuiMod_Shift) ? "Shift+" : "",
8337
0
        (key_chord & ImGuiMod_Alt) ? "Alt+" : "",
8338
0
        (key_chord & ImGuiMod_Super) ? (g.IO.ConfigMacOSXBehaviors ? "Cmd+" : "Super+") : "",
8339
0
        GetKeyName((ImGuiKey)(key_chord & ~ImGuiMod_Mask_)));
8340
0
}
8341
8342
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
8343
// t1 = current time (e.g.: g.Time)
8344
// An event is triggered at:
8345
//  t = 0.0f     t = repeat_delay,    t = repeat_delay + repeat_rate*N
8346
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
8347
10
{
8348
10
    if (t1 == 0.0f)
8349
0
        return 1;
8350
10
    if (t0 >= t1)
8351
0
        return 0;
8352
10
    if (repeat_rate <= 0.0f)
8353
0
        return (t0 < repeat_delay) && (t1 >= repeat_delay);
8354
10
    const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
8355
10
    const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
8356
10
    const int count = count_t1 - count_t0;
8357
10
    return count;
8358
10
}
8359
8360
void ImGui::GetTypematicRepeatRate(ImGuiInputFlags flags, float* repeat_delay, float* repeat_rate)
8361
206
{
8362
206
    ImGuiContext& g = *GImGui;
8363
206
    switch (flags & ImGuiInputFlags_RepeatRateMask_)
8364
206
    {
8365
22
    case ImGuiInputFlags_RepeatRateNavMove:             *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.80f; return;
8366
0
    case ImGuiInputFlags_RepeatRateNavTweak:            *repeat_delay = g.IO.KeyRepeatDelay * 0.72f; *repeat_rate = g.IO.KeyRepeatRate * 0.30f; return;
8367
184
    case ImGuiInputFlags_RepeatRateDefault: default:    *repeat_delay = g.IO.KeyRepeatDelay * 1.00f; *repeat_rate = g.IO.KeyRepeatRate * 1.00f; return;
8368
206
    }
8369
206
}
8370
8371
// Return value representing the number of presses in the last time period, for the given repeat rate
8372
// (most often returns 0 or 1. The result is generally only >1 when RepeatRate is smaller than DeltaTime, aka large DeltaTime or fast RepeatRate)
8373
int ImGui::GetKeyPressedAmount(ImGuiKey key, float repeat_delay, float repeat_rate)
8374
10
{
8375
10
    ImGuiContext& g = *GImGui;
8376
10
    const ImGuiKeyData* key_data = GetKeyData(key);
8377
10
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8378
0
        return 0;
8379
10
    const float t = key_data->DownDuration;
8380
10
    return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, repeat_delay, repeat_rate);
8381
10
}
8382
8383
// Return 2D vector representing the combination of four cardinal direction, with analog value support (for e.g. ImGuiKey_GamepadLStick* values).
8384
ImVec2 ImGui::GetKeyMagnitude2d(ImGuiKey key_left, ImGuiKey key_right, ImGuiKey key_up, ImGuiKey key_down)
8385
0
{
8386
0
    return ImVec2(
8387
0
        GetKeyData(key_right)->AnalogValue - GetKeyData(key_left)->AnalogValue,
8388
0
        GetKeyData(key_down)->AnalogValue - GetKeyData(key_up)->AnalogValue);
8389
0
}
8390
8391
// Rewrite routing data buffers to strip old entries + sort by key to make queries not touch scattered data.
8392
//   Entries   D,A,B,B,A,C,B     --> A,A,B,B,B,C,D
8393
//   Index     A:1 B:2 C:5 D:0   --> A:0 B:2 C:5 D:6
8394
// See 'Metrics->Key Owners & Shortcut Routing' to visualize the result of that operation.
8395
static void ImGui::UpdateKeyRoutingTable(ImGuiKeyRoutingTable* rt)
8396
34.4k
{
8397
34.4k
    ImGuiContext& g = *GImGui;
8398
34.4k
    rt->EntriesNext.resize(0);
8399
4.85M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8400
4.82M
    {
8401
4.82M
        const int new_routing_start_idx = rt->EntriesNext.Size;
8402
4.82M
        ImGuiKeyRoutingData* routing_entry;
8403
4.82M
        for (int old_routing_idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; old_routing_idx != -1; old_routing_idx = routing_entry->NextEntryIndex)
8404
0
        {
8405
0
            routing_entry = &rt->Entries[old_routing_idx];
8406
0
            routing_entry->RoutingCurr = routing_entry->RoutingNext; // Update entry
8407
0
            routing_entry->RoutingNext = ImGuiKeyOwner_None;
8408
0
            routing_entry->RoutingNextScore = 255;
8409
0
            if (routing_entry->RoutingCurr == ImGuiKeyOwner_None)
8410
0
                continue;
8411
0
            rt->EntriesNext.push_back(*routing_entry); // Write alive ones into new buffer
8412
8413
            // Apply routing to owner if there's no owner already (RoutingCurr == None at this point)
8414
0
            if (routing_entry->Mods == g.IO.KeyMods)
8415
0
            {
8416
0
                ImGuiKeyOwnerData* owner_data = ImGui::GetKeyOwnerData(key);
8417
0
                if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
8418
0
                    owner_data->OwnerCurr = routing_entry->RoutingCurr;
8419
0
            }
8420
0
        }
8421
8422
        // Rewrite linked-list
8423
4.82M
        rt->Index[key - ImGuiKey_NamedKey_BEGIN] = (ImGuiKeyRoutingIndex)(new_routing_start_idx < rt->EntriesNext.Size ? new_routing_start_idx : -1);
8424
4.82M
        for (int n = new_routing_start_idx; n < rt->EntriesNext.Size; n++)
8425
0
            rt->EntriesNext[n].NextEntryIndex = (ImGuiKeyRoutingIndex)((n + 1 < rt->EntriesNext.Size) ? n + 1 : -1);
8426
4.82M
    }
8427
34.4k
    rt->Entries.swap(rt->EntriesNext); // Swap new and old indexes
8428
34.4k
}
8429
8430
// owner_id may be None/Any, but routing_id needs to be always be set, so we default to GetCurrentFocusScope().
8431
static inline ImGuiID GetRoutingIdFromOwnerId(ImGuiID owner_id)
8432
0
{
8433
0
    ImGuiContext& g = *GImGui;
8434
0
    return (owner_id != ImGuiKeyOwner_None && owner_id != ImGuiKeyOwner_Any) ? owner_id : g.CurrentFocusScopeId;
8435
0
}
8436
8437
ImGuiKeyRoutingData* ImGui::GetShortcutRoutingData(ImGuiKeyChord key_chord)
8438
0
{
8439
    // Majority of shortcuts will be Key + any number of Mods
8440
    // We accept _Single_ mod with ImGuiKey_None.
8441
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl);                    // Legal
8442
    //  - Shortcut(ImGuiKey_S | ImGuiMod_Ctrl | ImGuiMod_Shift);   // Legal
8443
    //  - Shortcut(ImGuiMod_Ctrl);                                 // Legal
8444
    //  - Shortcut(ImGuiMod_Ctrl | ImGuiMod_Shift);                // Not legal
8445
0
    ImGuiContext& g = *GImGui;
8446
0
    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
8447
0
    ImGuiKeyRoutingData* routing_data;
8448
0
    if (key_chord & ImGuiMod_Shortcut)
8449
0
        key_chord = ConvertShortcutMod(key_chord);
8450
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
8451
0
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
8452
0
    if (key == ImGuiKey_None)
8453
0
        key = ConvertSingleModFlagToKey(mods);
8454
0
    IM_ASSERT(IsNamedKey(key));
8455
8456
    // Get (in the majority of case, the linked list will have one element so this should be 2 reads.
8457
    // Subsequent elements will be contiguous in memory as list is sorted/rebuilt in NewFrame).
8458
0
    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; idx = routing_data->NextEntryIndex)
8459
0
    {
8460
0
        routing_data = &rt->Entries[idx];
8461
0
        if (routing_data->Mods == mods)
8462
0
            return routing_data;
8463
0
    }
8464
8465
    // Add to linked-list
8466
0
    ImGuiKeyRoutingIndex routing_data_idx = (ImGuiKeyRoutingIndex)rt->Entries.Size;
8467
0
    rt->Entries.push_back(ImGuiKeyRoutingData());
8468
0
    routing_data = &rt->Entries[routing_data_idx];
8469
0
    routing_data->Mods = (ImU16)mods;
8470
0
    routing_data->NextEntryIndex = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; // Setup linked list
8471
0
    rt->Index[key - ImGuiKey_NamedKey_BEGIN] = routing_data_idx;
8472
0
    return routing_data;
8473
0
}
8474
8475
// Current score encoding (lower is highest priority):
8476
//  -   0: ImGuiInputFlags_RouteGlobalHigh
8477
//  -   1: ImGuiInputFlags_RouteFocused (if item active)
8478
//  -   2: ImGuiInputFlags_RouteGlobal
8479
//  -  3+: ImGuiInputFlags_RouteFocused (if window in focus-stack)
8480
//  - 254: ImGuiInputFlags_RouteGlobalLow
8481
//  - 255: never route
8482
// 'flags' should include an explicit routing policy
8483
static int CalcRoutingScore(ImGuiWindow* location, ImGuiID owner_id, ImGuiInputFlags flags)
8484
0
{
8485
0
    if (flags & ImGuiInputFlags_RouteFocused)
8486
0
    {
8487
0
        ImGuiContext& g = *GImGui;
8488
0
        ImGuiWindow* focused = g.NavWindow;
8489
8490
        // ActiveID gets top priority
8491
        // (we don't check g.ActiveIdUsingAllKeys here. Routing is applied but if input ownership is tested later it may discard it)
8492
0
        if (owner_id != 0 && g.ActiveId == owner_id)
8493
0
            return 1;
8494
8495
        // Score based on distance to focused window (lower is better)
8496
        // Assuming both windows are submitting a routing request,
8497
        // - When Window....... is focused -> Window scores 3 (best), Window/ChildB scores 255 (no match)
8498
        // - When Window/ChildB is focused -> Window scores 4,        Window/ChildB scores 3 (best)
8499
        // Assuming only WindowA is submitting a routing request,
8500
        // - When Window/ChildB is focused -> Window scores 4 (best), Window/ChildB doesn't have a score.
8501
0
        if (focused != NULL && focused->RootWindow == location->RootWindow)
8502
0
            for (int next_score = 3; focused != NULL; next_score++)
8503
0
            {
8504
0
                if (focused == location)
8505
0
                {
8506
0
                    IM_ASSERT(next_score < 255);
8507
0
                    return next_score;
8508
0
                }
8509
0
                focused = (focused->RootWindow != focused) ? focused->ParentWindow : NULL; // FIXME: This could be later abstracted as a focus path
8510
0
            }
8511
0
        return 255;
8512
0
    }
8513
8514
    // ImGuiInputFlags_RouteGlobalHigh is default, so calls without flags are not conditional
8515
0
    if (flags & ImGuiInputFlags_RouteGlobal)
8516
0
        return 2;
8517
0
    if (flags & ImGuiInputFlags_RouteGlobalLow)
8518
0
        return 254;
8519
0
    return 0;
8520
0
}
8521
8522
// Request a desired route for an input chord (key + mods).
8523
// Return true if the route is available this frame.
8524
// - Routes and key ownership are attributed at the beginning of next frame based on best score and mod state.
8525
//   (Conceptually this does a "Submit for next frame" + "Test for current frame".
8526
//   As such, it could be called TrySetXXX or SubmitXXX, or the Submit and Test operations should be separate.)
8527
// - Using 'owner_id == ImGuiKeyOwner_Any/0': auto-assign an owner based on current focus scope (each window has its focus scope by default)
8528
// - Using 'owner_id == ImGuiKeyOwner_None': allows disabling/locking a shortcut.
8529
bool ImGui::SetShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
8530
68.8k
{
8531
68.8k
    ImGuiContext& g = *GImGui;
8532
68.8k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
8533
0
        flags |= ImGuiInputFlags_RouteGlobalHigh; // IMPORTANT: This is the default for SetShortcutRouting() but NOT Shortcut()
8534
68.8k
    else
8535
68.8k
        IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiInputFlags_RouteMask_)); // Check that only 1 routing flag is used
8536
8537
68.8k
    if (flags & ImGuiInputFlags_RouteUnlessBgFocused)
8538
0
        if (g.NavWindow == NULL)
8539
0
            return false;
8540
68.8k
    if (flags & ImGuiInputFlags_RouteAlways)
8541
68.8k
        return true;
8542
8543
0
    const int score = CalcRoutingScore(g.CurrentWindow, owner_id, flags);
8544
0
    if (score == 255)
8545
0
        return false;
8546
8547
    // Submit routing for NEXT frame (assuming score is sufficient)
8548
    // FIXME: Could expose a way to use a "serve last" policy for same score resolution (using <= instead of <).
8549
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord);
8550
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8551
    //const bool set_route = (flags & ImGuiInputFlags_ServeLast) ? (score <= routing_data->RoutingNextScore) : (score < routing_data->RoutingNextScore);
8552
0
    if (score < routing_data->RoutingNextScore)
8553
0
    {
8554
0
        routing_data->RoutingNext = routing_id;
8555
0
        routing_data->RoutingNextScore = (ImU8)score;
8556
0
    }
8557
8558
    // Return routing state for CURRENT frame
8559
0
    return routing_data->RoutingCurr == routing_id;
8560
0
}
8561
8562
// Currently unused by core (but used by tests)
8563
// Note: this cannot be turned into GetShortcutRouting() because we do the owner_id->routing_id translation, name would be more misleading.
8564
bool ImGui::TestShortcutRouting(ImGuiKeyChord key_chord, ImGuiID owner_id)
8565
0
{
8566
0
    const ImGuiID routing_id = GetRoutingIdFromOwnerId(owner_id);
8567
0
    ImGuiKeyRoutingData* routing_data = GetShortcutRoutingData(key_chord); // FIXME: Could avoid creating entry.
8568
0
    return routing_data->RoutingCurr == routing_id;
8569
0
}
8570
8571
// Note that Dear ImGui doesn't know the meaning/semantic of ImGuiKey from 0..511: they are legacy native keycodes.
8572
// Consider transitioning from 'IsKeyDown(MY_ENGINE_KEY_A)' (<1.87) to IsKeyDown(ImGuiKey_A) (>= 1.87)
8573
bool ImGui::IsKeyDown(ImGuiKey key)
8574
516k
{
8575
516k
    return IsKeyDown(key, ImGuiKeyOwner_Any);
8576
516k
}
8577
8578
bool ImGui::IsKeyDown(ImGuiKey key, ImGuiID owner_id)
8579
519k
{
8580
519k
    const ImGuiKeyData* key_data = GetKeyData(key);
8581
519k
    if (!key_data->Down)
8582
509k
        return false;
8583
10.0k
    if (!TestKeyOwner(key, owner_id))
8584
0
        return false;
8585
10.0k
    return true;
8586
10.0k
}
8587
8588
bool ImGui::IsKeyPressed(ImGuiKey key, bool repeat)
8589
12.1k
{
8590
12.1k
    return IsKeyPressed(key, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8591
12.1k
}
8592
8593
// Important: unless legacy IsKeyPressed(ImGuiKey, bool repeat=true) which DEFAULT to repeat, this requires EXPLICIT repeat.
8594
bool ImGui::IsKeyPressed(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
8595
89.8k
{
8596
89.8k
    const ImGuiKeyData* key_data = GetKeyData(key);
8597
89.8k
    if (!key_data->Down) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8598
86.3k
        return false;
8599
3.48k
    const float t = key_data->DownDuration;
8600
3.48k
    if (t < 0.0f)
8601
0
        return false;
8602
3.48k
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8603
8604
3.48k
    bool pressed = (t == 0.0f);
8605
3.48k
    if (!pressed && ((flags & ImGuiInputFlags_Repeat) != 0))
8606
206
    {
8607
206
        float repeat_delay, repeat_rate;
8608
206
        GetTypematicRepeatRate(flags, &repeat_delay, &repeat_rate);
8609
206
        pressed = (t > repeat_delay) && GetKeyPressedAmount(key, repeat_delay, repeat_rate) > 0;
8610
206
    }
8611
3.48k
    if (!pressed)
8612
3.13k
        return false;
8613
347
    if (!TestKeyOwner(key, owner_id))
8614
0
        return false;
8615
347
    return true;
8616
347
}
8617
8618
bool ImGui::IsKeyReleased(ImGuiKey key)
8619
0
{
8620
0
    return IsKeyReleased(key, ImGuiKeyOwner_Any);
8621
0
}
8622
8623
bool ImGui::IsKeyReleased(ImGuiKey key, ImGuiID owner_id)
8624
0
{
8625
0
    const ImGuiKeyData* key_data = GetKeyData(key);
8626
0
    if (key_data->DownDurationPrev < 0.0f || key_data->Down)
8627
0
        return false;
8628
0
    if (!TestKeyOwner(key, owner_id))
8629
0
        return false;
8630
0
    return true;
8631
0
}
8632
8633
bool ImGui::IsMouseDown(ImGuiMouseButton button)
8634
9
{
8635
9
    ImGuiContext& g = *GImGui;
8636
9
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8637
9
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // should be same as IsKeyDown(MouseButtonToKey(button), ImGuiKeyOwner_Any), but this allows legacy code hijacking the io.Mousedown[] array.
8638
9
}
8639
8640
bool ImGui::IsMouseDown(ImGuiMouseButton button, ImGuiID owner_id)
8641
404
{
8642
404
    ImGuiContext& g = *GImGui;
8643
404
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8644
404
    return g.IO.MouseDown[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyDown(MouseButtonToKey(button), owner_id), but this allows legacy code hijacking the io.Mousedown[] array.
8645
404
}
8646
8647
bool ImGui::IsMouseClicked(ImGuiMouseButton button, bool repeat)
8648
78
{
8649
78
    return IsMouseClicked(button, ImGuiKeyOwner_Any, repeat ? ImGuiInputFlags_Repeat : ImGuiInputFlags_None);
8650
78
}
8651
8652
bool ImGui::IsMouseClicked(ImGuiMouseButton button, ImGuiID owner_id, ImGuiInputFlags flags)
8653
1.08k
{
8654
1.08k
    ImGuiContext& g = *GImGui;
8655
1.08k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8656
1.08k
    if (!g.IO.MouseDown[button]) // In theory this should already be encoded as (DownDuration < 0.0f), but testing this facilitates eating mechanism (until we finish work on key ownership)
8657
777
        return false;
8658
312
    const float t = g.IO.MouseDownDuration[button];
8659
312
    if (t < 0.0f)
8660
0
        return false;
8661
312
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByIsKeyPressed) == 0); // Passing flags not supported by this function!
8662
8663
312
    const bool repeat = (flags & ImGuiInputFlags_Repeat) != 0;
8664
312
    const bool pressed = (t == 0.0f) || (repeat && t > g.IO.KeyRepeatDelay && CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0);
8665
312
    if (!pressed)
8666
145
        return false;
8667
8668
167
    if (!TestKeyOwner(MouseButtonToKey(button), owner_id))
8669
0
        return false;
8670
8671
167
    return true;
8672
167
}
8673
8674
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
8675
0
{
8676
0
    ImGuiContext& g = *GImGui;
8677
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8678
0
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any); // Should be same as IsKeyReleased(MouseButtonToKey(button), ImGuiKeyOwner_Any)
8679
0
}
8680
8681
bool ImGui::IsMouseReleased(ImGuiMouseButton button, ImGuiID owner_id)
8682
1.01k
{
8683
1.01k
    ImGuiContext& g = *GImGui;
8684
1.01k
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8685
1.01k
    return g.IO.MouseReleased[button] && TestKeyOwner(MouseButtonToKey(button), owner_id); // Should be same as IsKeyReleased(MouseButtonToKey(button), owner_id)
8686
1.01k
}
8687
8688
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
8689
60
{
8690
60
    ImGuiContext& g = *GImGui;
8691
60
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8692
60
    return g.IO.MouseClickedCount[button] == 2 && TestKeyOwner(MouseButtonToKey(button), ImGuiKeyOwner_Any);
8693
60
}
8694
8695
int ImGui::GetMouseClickedCount(ImGuiMouseButton button)
8696
0
{
8697
0
    ImGuiContext& g = *GImGui;
8698
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8699
0
    return g.IO.MouseClickedCount[button];
8700
0
}
8701
8702
// Test if mouse cursor is hovering given rectangle
8703
// NB- Rectangle is clipped by our current clip setting
8704
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
8705
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
8706
151k
{
8707
151k
    ImGuiContext& g = *GImGui;
8708
8709
    // Clip
8710
151k
    ImRect rect_clipped(r_min, r_max);
8711
151k
    if (clip)
8712
79.5k
        rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
8713
8714
    // Expand for touch input
8715
151k
    const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
8716
151k
    if (!rect_for_touch.Contains(g.IO.MousePos))
8717
145k
        return false;
8718
5.92k
    if (!g.MouseViewport->GetMainRect().Overlaps(rect_clipped))
8719
0
        return false;
8720
5.92k
    return true;
8721
5.92k
}
8722
8723
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
8724
// [Internal] This doesn't test if the button is pressed
8725
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton button, float lock_threshold)
8726
270
{
8727
270
    ImGuiContext& g = *GImGui;
8728
270
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8729
270
    if (lock_threshold < 0.0f)
8730
252
        lock_threshold = g.IO.MouseDragThreshold;
8731
270
    return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
8732
270
}
8733
8734
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
8735
311
{
8736
311
    ImGuiContext& g = *GImGui;
8737
311
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8738
311
    if (!g.IO.MouseDown[button])
8739
41
        return false;
8740
270
    return IsMouseDragPastThreshold(button, lock_threshold);
8741
311
}
8742
8743
ImVec2 ImGui::GetMousePos()
8744
987
{
8745
987
    ImGuiContext& g = *GImGui;
8746
987
    return g.IO.MousePos;
8747
987
}
8748
8749
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
8750
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
8751
0
{
8752
0
    ImGuiContext& g = *GImGui;
8753
0
    if (g.BeginPopupStack.Size > 0)
8754
0
        return g.OpenPopupStack[g.BeginPopupStack.Size - 1].OpenMousePos;
8755
0
    return g.IO.MousePos;
8756
0
}
8757
8758
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
8759
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
8760
104k
{
8761
    // The assert is only to silence a false-positive in XCode Static Analysis.
8762
    // Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
8763
104k
    IM_ASSERT(GImGui != NULL);
8764
104k
    const float MOUSE_INVALID = -256000.0f;
8765
104k
    ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
8766
104k
    return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
8767
104k
}
8768
8769
// [WILL OBSOLETE] This was designed for backends, but prefer having backend maintain a mask of held mouse buttons, because upcoming input queue system will make this invalid.
8770
bool ImGui::IsAnyMouseDown()
8771
0
{
8772
0
    ImGuiContext& g = *GImGui;
8773
0
    for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
8774
0
        if (g.IO.MouseDown[n])
8775
0
            return true;
8776
0
    return false;
8777
0
}
8778
8779
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
8780
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
8781
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
8782
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton button, float lock_threshold)
8783
0
{
8784
0
    ImGuiContext& g = *GImGui;
8785
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8786
0
    if (lock_threshold < 0.0f)
8787
0
        lock_threshold = g.IO.MouseDragThreshold;
8788
0
    if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
8789
0
        if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
8790
0
            if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
8791
0
                return g.IO.MousePos - g.IO.MouseClickedPos[button];
8792
0
    return ImVec2(0.0f, 0.0f);
8793
0
}
8794
8795
void ImGui::ResetMouseDragDelta(ImGuiMouseButton button)
8796
0
{
8797
0
    ImGuiContext& g = *GImGui;
8798
0
    IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
8799
    // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
8800
0
    g.IO.MouseClickedPos[button] = g.IO.MousePos;
8801
0
}
8802
8803
// Get desired mouse cursor shape.
8804
// Important: this is meant to be used by a platform backend, it is reset in ImGui::NewFrame(),
8805
// updated during the frame, and locked in EndFrame()/Render().
8806
// If you use software rendering by setting io.MouseDrawCursor then Dear ImGui will render those for you
8807
ImGuiMouseCursor ImGui::GetMouseCursor()
8808
0
{
8809
0
    ImGuiContext& g = *GImGui;
8810
0
    return g.MouseCursor;
8811
0
}
8812
8813
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
8814
13
{
8815
13
    ImGuiContext& g = *GImGui;
8816
13
    g.MouseCursor = cursor_type;
8817
13
}
8818
8819
static void UpdateAliasKey(ImGuiKey key, bool v, float analog_value)
8820
241k
{
8821
241k
    IM_ASSERT(ImGui::IsAliasKey(key));
8822
241k
    ImGuiKeyData* key_data = ImGui::GetKeyData(key);
8823
241k
    key_data->Down = v;
8824
241k
    key_data->AnalogValue = analog_value;
8825
241k
}
8826
8827
// [Internal] Do not use directly
8828
static ImGuiKeyChord GetMergedModsFromKeys()
8829
68.8k
{
8830
68.8k
    ImGuiKeyChord mods = 0;
8831
68.8k
    if (ImGui::IsKeyDown(ImGuiMod_Ctrl))     { mods |= ImGuiMod_Ctrl; }
8832
68.8k
    if (ImGui::IsKeyDown(ImGuiMod_Shift))    { mods |= ImGuiMod_Shift; }
8833
68.8k
    if (ImGui::IsKeyDown(ImGuiMod_Alt))      { mods |= ImGuiMod_Alt; }
8834
68.8k
    if (ImGui::IsKeyDown(ImGuiMod_Super))    { mods |= ImGuiMod_Super; }
8835
68.8k
    return mods;
8836
68.8k
}
8837
8838
static void ImGui::UpdateKeyboardInputs()
8839
34.4k
{
8840
34.4k
    ImGuiContext& g = *GImGui;
8841
34.4k
    ImGuiIO& io = g.IO;
8842
8843
    // Import legacy keys or verify they are not used
8844
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8845
    if (io.BackendUsingLegacyKeyArrays == 0)
8846
    {
8847
        // Backend used new io.AddKeyEvent() API: Good! Verify that old arrays are never written to externally.
8848
        for (int n = 0; n < ImGuiKey_LegacyNativeKey_END; n++)
8849
            IM_ASSERT((io.KeysDown[n] == false || IsKeyDown((ImGuiKey)n)) && "Backend needs to either only use io.AddKeyEvent(), either only fill legacy io.KeysDown[] + io.KeyMap[]. Not both!");
8850
    }
8851
    else
8852
    {
8853
        if (g.FrameCount == 0)
8854
            for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8855
                IM_ASSERT(g.IO.KeyMap[n] == -1 && "Backend is not allowed to write to io.KeyMap[0..511]!");
8856
8857
        // Build reverse KeyMap (Named -> Legacy)
8858
        for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_NamedKey_END; n++)
8859
            if (io.KeyMap[n] != -1)
8860
            {
8861
                IM_ASSERT(IsLegacyKey((ImGuiKey)io.KeyMap[n]));
8862
                io.KeyMap[io.KeyMap[n]] = n;
8863
            }
8864
8865
        // Import legacy keys into new ones
8866
        for (int n = ImGuiKey_LegacyNativeKey_BEGIN; n < ImGuiKey_LegacyNativeKey_END; n++)
8867
            if (io.KeysDown[n] || io.BackendUsingLegacyKeyArrays == 1)
8868
            {
8869
                const ImGuiKey key = (ImGuiKey)(io.KeyMap[n] != -1 ? io.KeyMap[n] : n);
8870
                IM_ASSERT(io.KeyMap[n] == -1 || IsNamedKey(key));
8871
                io.KeysData[key].Down = io.KeysDown[n];
8872
                if (key != n)
8873
                    io.KeysDown[key] = io.KeysDown[n]; // Allow legacy code using io.KeysDown[GetKeyIndex()] with old backends
8874
                io.BackendUsingLegacyKeyArrays = 1;
8875
            }
8876
        if (io.BackendUsingLegacyKeyArrays == 1)
8877
        {
8878
            GetKeyData(ImGuiMod_Ctrl)->Down = io.KeyCtrl;
8879
            GetKeyData(ImGuiMod_Shift)->Down = io.KeyShift;
8880
            GetKeyData(ImGuiMod_Alt)->Down = io.KeyAlt;
8881
            GetKeyData(ImGuiMod_Super)->Down = io.KeySuper;
8882
        }
8883
    }
8884
8885
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
8886
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
8887
    if (io.BackendUsingLegacyNavInputArray && nav_gamepad_active)
8888
    {
8889
        #define MAP_LEGACY_NAV_INPUT_TO_KEY1(_KEY, _NAV1)           do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f); io.KeysData[_KEY].AnalogValue = io.NavInputs[_NAV1]; } while (0)
8890
        #define MAP_LEGACY_NAV_INPUT_TO_KEY2(_KEY, _NAV1, _NAV2)    do { io.KeysData[_KEY].Down = (io.NavInputs[_NAV1] > 0.0f) || (io.NavInputs[_NAV2] > 0.0f); io.KeysData[_KEY].AnalogValue = ImMax(io.NavInputs[_NAV1], io.NavInputs[_NAV2]); } while (0)
8891
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceDown, ImGuiNavInput_Activate);
8892
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceRight, ImGuiNavInput_Cancel);
8893
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceLeft, ImGuiNavInput_Menu);
8894
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadFaceUp, ImGuiNavInput_Input);
8895
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadLeft, ImGuiNavInput_DpadLeft);
8896
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadRight, ImGuiNavInput_DpadRight);
8897
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadUp, ImGuiNavInput_DpadUp);
8898
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadDpadDown, ImGuiNavInput_DpadDown);
8899
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadL1, ImGuiNavInput_FocusPrev, ImGuiNavInput_TweakSlow);
8900
        MAP_LEGACY_NAV_INPUT_TO_KEY2(ImGuiKey_GamepadR1, ImGuiNavInput_FocusNext, ImGuiNavInput_TweakFast);
8901
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickLeft, ImGuiNavInput_LStickLeft);
8902
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickRight, ImGuiNavInput_LStickRight);
8903
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickUp, ImGuiNavInput_LStickUp);
8904
        MAP_LEGACY_NAV_INPUT_TO_KEY1(ImGuiKey_GamepadLStickDown, ImGuiNavInput_LStickDown);
8905
        #undef NAV_MAP_KEY
8906
    }
8907
#endif
8908
#endif
8909
8910
    // Update aliases
8911
206k
    for (int n = 0; n < ImGuiMouseButton_COUNT; n++)
8912
172k
        UpdateAliasKey(MouseButtonToKey(n), io.MouseDown[n], io.MouseDown[n] ? 1.0f : 0.0f);
8913
34.4k
    UpdateAliasKey(ImGuiKey_MouseWheelX, io.MouseWheelH != 0.0f, io.MouseWheelH);
8914
34.4k
    UpdateAliasKey(ImGuiKey_MouseWheelY, io.MouseWheel != 0.0f, io.MouseWheel);
8915
8916
    // Synchronize io.KeyMods and io.KeyXXX values.
8917
    // - New backends (1.87+): send io.AddKeyEvent(ImGuiMod_XXX) ->                                      -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8918
    // - Legacy backends:      set io.KeyXXX bools               -> (above) set key array from io.KeyXXX -> (here) deriving io.KeyMods + io.KeyXXX from key array.
8919
    // So with legacy backends the 4 values will do a unnecessary back-and-forth but it makes the code simpler and future facing.
8920
34.4k
    io.KeyMods = GetMergedModsFromKeys();
8921
34.4k
    io.KeyCtrl = (io.KeyMods & ImGuiMod_Ctrl) != 0;
8922
34.4k
    io.KeyShift = (io.KeyMods & ImGuiMod_Shift) != 0;
8923
34.4k
    io.KeyAlt = (io.KeyMods & ImGuiMod_Alt) != 0;
8924
34.4k
    io.KeySuper = (io.KeyMods & ImGuiMod_Super) != 0;
8925
8926
    // Clear gamepad data if disabled
8927
34.4k
    if ((io.BackendFlags & ImGuiBackendFlags_HasGamepad) == 0)
8928
861k
        for (int i = ImGuiKey_Gamepad_BEGIN; i < ImGuiKey_Gamepad_END; i++)
8929
826k
        {
8930
826k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].Down = false;
8931
826k
            io.KeysData[i - ImGuiKey_KeysData_OFFSET].AnalogValue = 0.0f;
8932
826k
        }
8933
8934
    // Update keys
8935
4.85M
    for (int i = 0; i < ImGuiKey_KeysData_SIZE; i++)
8936
4.82M
    {
8937
4.82M
        ImGuiKeyData* key_data = &io.KeysData[i];
8938
4.82M
        key_data->DownDurationPrev = key_data->DownDuration;
8939
4.82M
        key_data->DownDuration = key_data->Down ? (key_data->DownDuration < 0.0f ? 0.0f : key_data->DownDuration + io.DeltaTime) : -1.0f;
8940
4.82M
    }
8941
8942
    // Update keys/input owner (named keys only): one entry per key
8943
4.85M
    for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
8944
4.82M
    {
8945
4.82M
        ImGuiKeyData* key_data = &io.KeysData[key - ImGuiKey_KeysData_OFFSET];
8946
4.82M
        ImGuiKeyOwnerData* owner_data = &g.KeysOwnerData[key - ImGuiKey_NamedKey_BEGIN];
8947
4.82M
        owner_data->OwnerCurr = owner_data->OwnerNext;
8948
4.82M
        if (!key_data->Down) // Important: ownership is released on the frame after a release. Ensure a 'MouseDown -> CloseWindow -> MouseUp' chain doesn't lead to someone else seeing the MouseUp.
8949
4.78M
            owner_data->OwnerNext = ImGuiKeyOwner_None;
8950
4.82M
        owner_data->LockThisFrame = owner_data->LockUntilRelease = owner_data->LockUntilRelease && key_data->Down;  // Clear LockUntilRelease when key is not Down anymore
8951
4.82M
    }
8952
8953
34.4k
    UpdateKeyRoutingTable(&g.KeysRoutingTable);
8954
34.4k
}
8955
8956
static void ImGui::UpdateMouseInputs()
8957
34.4k
{
8958
34.4k
    ImGuiContext& g = *GImGui;
8959
34.4k
    ImGuiIO& io = g.IO;
8960
8961
    // Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
8962
34.4k
    if (IsMousePosValid(&io.MousePos))
8963
13.8k
        io.MousePos = g.MouseLastValidPos = ImFloorSigned(io.MousePos);
8964
8965
    // If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
8966
34.4k
    if (IsMousePosValid(&io.MousePos) && IsMousePosValid(&io.MousePosPrev))
8967
13.1k
        io.MouseDelta = io.MousePos - io.MousePosPrev;
8968
21.3k
    else
8969
21.3k
        io.MouseDelta = ImVec2(0.0f, 0.0f);
8970
8971
    // If mouse moved we re-enable mouse hovering in case it was disabled by gamepad/keyboard. In theory should use a >0.0f threshold but would need to reset in everywhere we set this to true.
8972
34.4k
    if (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f)
8973
797
        g.NavDisableMouseHover = false;
8974
8975
34.4k
    io.MousePosPrev = io.MousePos;
8976
206k
    for (int i = 0; i < IM_ARRAYSIZE(io.MouseDown); i++)
8977
172k
    {
8978
172k
        io.MouseClicked[i] = io.MouseDown[i] && io.MouseDownDuration[i] < 0.0f;
8979
172k
        io.MouseClickedCount[i] = 0; // Will be filled below
8980
172k
        io.MouseReleased[i] = !io.MouseDown[i] && io.MouseDownDuration[i] >= 0.0f;
8981
172k
        io.MouseDownDurationPrev[i] = io.MouseDownDuration[i];
8982
172k
        io.MouseDownDuration[i] = io.MouseDown[i] ? (io.MouseDownDuration[i] < 0.0f ? 0.0f : io.MouseDownDuration[i] + io.DeltaTime) : -1.0f;
8983
172k
        if (io.MouseClicked[i])
8984
2.92k
        {
8985
2.92k
            bool is_repeated_click = false;
8986
2.92k
            if ((float)(g.Time - io.MouseClickedTime[i]) < io.MouseDoubleClickTime)
8987
2.00k
            {
8988
2.00k
                ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
8989
2.00k
                if (ImLengthSqr(delta_from_click_pos) < io.MouseDoubleClickMaxDist * io.MouseDoubleClickMaxDist)
8990
1.74k
                    is_repeated_click = true;
8991
2.00k
            }
8992
2.92k
            if (is_repeated_click)
8993
1.74k
                io.MouseClickedLastCount[i]++;
8994
1.18k
            else
8995
1.18k
                io.MouseClickedLastCount[i] = 1;
8996
2.92k
            io.MouseClickedTime[i] = g.Time;
8997
2.92k
            io.MouseClickedPos[i] = io.MousePos;
8998
2.92k
            io.MouseClickedCount[i] = io.MouseClickedLastCount[i];
8999
2.92k
            io.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
9000
2.92k
            io.MouseDragMaxDistanceSqr[i] = 0.0f;
9001
2.92k
        }
9002
169k
        else if (io.MouseDown[i])
9003
16.8k
        {
9004
            // Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
9005
16.8k
            ImVec2 delta_from_click_pos = IsMousePosValid(&io.MousePos) ? (io.MousePos - io.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
9006
16.8k
            io.MouseDragMaxDistanceSqr[i] = ImMax(io.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
9007
16.8k
            io.MouseDragMaxDistanceAbs[i].x = ImMax(io.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
9008
16.8k
            io.MouseDragMaxDistanceAbs[i].y = ImMax(io.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
9009
16.8k
        }
9010
9011
        // We provide io.MouseDoubleClicked[] as a legacy service
9012
172k
        io.MouseDoubleClicked[i] = (io.MouseClickedCount[i] == 2);
9013
9014
        // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
9015
172k
        if (io.MouseClicked[i])
9016
2.92k
            g.NavDisableMouseHover = false;
9017
172k
    }
9018
34.4k
}
9019
9020
static void LockWheelingWindow(ImGuiWindow* window, float wheel_amount)
9021
37
{
9022
37
    ImGuiContext& g = *GImGui;
9023
37
    if (window)
9024
21
        g.WheelingWindowReleaseTimer = ImMin(g.WheelingWindowReleaseTimer + ImAbs(wheel_amount) * WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER, WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER);
9025
16
    else
9026
16
        g.WheelingWindowReleaseTimer = 0.0f;
9027
37
    if (g.WheelingWindow == window)
9028
5
        return;
9029
32
    IMGUI_DEBUG_LOG_IO("LockWheelingWindow() \"%s\"\n", window ? window->Name : "NULL");
9030
32
    g.WheelingWindow = window;
9031
32
    g.WheelingWindowRefMousePos = g.IO.MousePos;
9032
32
    if (window == NULL)
9033
16
    {
9034
16
        g.WheelingWindowStartFrame = -1;
9035
16
        g.WheelingAxisAvg = ImVec2(0.0f, 0.0f);
9036
16
    }
9037
32
}
9038
9039
static ImGuiWindow* FindBestWheelingWindow(const ImVec2& wheel)
9040
55
{
9041
    // For each axis, find window in the hierarchy that may want to use scrolling
9042
55
    ImGuiContext& g = *GImGui;
9043
55
    ImGuiWindow* windows[2] = { NULL, NULL };
9044
165
    for (int axis = 0; axis < 2; axis++)
9045
110
        if (wheel[axis] != 0.0f)
9046
94
            for (ImGuiWindow* window = windows[axis] = g.HoveredWindow; window->Flags & ImGuiWindowFlags_ChildWindow; window = windows[axis] = window->ParentWindow)
9047
16
            {
9048
                // Bubble up into parent window if:
9049
                // - a child window doesn't allow any scrolling.
9050
                // - a child window has the ImGuiWindowFlags_NoScrollWithMouse flag.
9051
                //// - a child window doesn't need scrolling because it is already at the edge for the direction we are going in (FIXME-WIP)
9052
16
                const bool has_scrolling = (window->ScrollMax[axis] != 0.0f);
9053
16
                const bool inputs_disabled = (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
9054
                //const bool scrolling_past_limits = (wheel_v < 0.0f) ? (window->Scroll[axis] <= 0.0f) : (window->Scroll[axis] >= window->ScrollMax[axis]);
9055
16
                if (has_scrolling && !inputs_disabled) // && !scrolling_past_limits)
9056
6
                    break; // select this window
9057
16
            }
9058
55
    if (windows[0] == NULL && windows[1] == NULL)
9059
0
        return NULL;
9060
9061
    // If there's only one window or only one axis then there's no ambiguity
9062
55
    if (windows[0] == windows[1] || windows[0] == NULL || windows[1] == NULL)
9063
50
        return windows[1] ? windows[1] : windows[0];
9064
9065
    // If candidate are different windows we need to decide which one to prioritize
9066
    // - First frame: only find a winner if one axis is zero.
9067
    // - Subsequent frames: only find a winner when one is more than the other.
9068
5
    if (g.WheelingWindowStartFrame == -1)
9069
2
        g.WheelingWindowStartFrame = g.FrameCount;
9070
5
    if ((g.WheelingWindowStartFrame == g.FrameCount && wheel.x != 0.0f && wheel.y != 0.0f) || (g.WheelingAxisAvg.x == g.WheelingAxisAvg.y))
9071
2
    {
9072
2
        g.WheelingWindowWheelRemainder = wheel;
9073
2
        return NULL;
9074
2
    }
9075
3
    return (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? windows[0] : windows[1];
9076
5
}
9077
9078
// Called by NewFrame()
9079
void ImGui::UpdateMouseWheel()
9080
34.4k
{
9081
    // Reset the locked window if we move the mouse or after the timer elapses.
9082
    // FIXME: Ideally we could refactor to have one timer for "changing window w/ same axis" and a shorter timer for "changing window or axis w/ other axis" (#3795)
9083
34.4k
    ImGuiContext& g = *GImGui;
9084
34.4k
    if (g.WheelingWindow != NULL)
9085
111
    {
9086
111
        g.WheelingWindowReleaseTimer -= g.IO.DeltaTime;
9087
111
        if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
9088
4
            g.WheelingWindowReleaseTimer = 0.0f;
9089
111
        if (g.WheelingWindowReleaseTimer <= 0.0f)
9090
16
            LockWheelingWindow(NULL, 0.0f);
9091
111
    }
9092
9093
34.4k
    ImVec2 wheel;
9094
34.4k
    wheel.x = TestKeyOwner(ImGuiKey_MouseWheelX, ImGuiKeyOwner_None) ? g.IO.MouseWheelH : 0.0f;
9095
34.4k
    wheel.y = TestKeyOwner(ImGuiKey_MouseWheelY, ImGuiKeyOwner_None) ? g.IO.MouseWheel : 0.0f;
9096
9097
    //IMGUI_DEBUG_LOG("MouseWheel X:%.3f Y:%.3f\n", wheel_x, wheel_y);
9098
34.4k
    ImGuiWindow* mouse_window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
9099
34.4k
    if (!mouse_window || mouse_window->Collapsed)
9100
33.8k
        return;
9101
9102
    // Zoom / Scale window
9103
    // FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
9104
602
    if (wheel.y != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
9105
0
    {
9106
0
        LockWheelingWindow(mouse_window, wheel.y);
9107
0
        ImGuiWindow* window = mouse_window;
9108
0
        const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
9109
0
        const float scale = new_font_scale / window->FontWindowScale;
9110
0
        window->FontWindowScale = new_font_scale;
9111
0
        if (window == window->RootWindow)
9112
0
        {
9113
0
            const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
9114
0
            SetWindowPos(window, window->Pos + offset, 0);
9115
0
            window->Size = ImFloor(window->Size * scale);
9116
0
            window->SizeFull = ImFloor(window->SizeFull * scale);
9117
0
        }
9118
0
        return;
9119
0
    }
9120
602
    if (g.IO.KeyCtrl)
9121
0
        return;
9122
9123
    // Mouse wheel scrolling
9124
    // As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
9125
    // - We avoid doing it on OSX as it the OS input layer handles this already.
9126
    // - However this means when running on OSX over Emcripten, Shift+WheelY will incur two swappings (1 in OS, 1 here), cancelling the feature.
9127
602
    const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
9128
602
    if (swap_axis)
9129
0
    {
9130
0
        wheel.x = wheel.y;
9131
0
        wheel.y = 0.0f;
9132
0
    }
9133
9134
    // Maintain a rough average of moving magnitude on both axises
9135
    // FIXME: should by based on wall clock time rather than frame-counter
9136
602
    g.WheelingAxisAvg.x = ImExponentialMovingAverage(g.WheelingAxisAvg.x, ImAbs(wheel.x), 30);
9137
602
    g.WheelingAxisAvg.y = ImExponentialMovingAverage(g.WheelingAxisAvg.y, ImAbs(wheel.y), 30);
9138
9139
    // In the rare situation where FindBestWheelingWindow() had to defer first frame of wheeling due to ambiguous main axis, reinject it now.
9140
602
    wheel += g.WheelingWindowWheelRemainder;
9141
602
    g.WheelingWindowWheelRemainder = ImVec2(0.0f, 0.0f);
9142
602
    if (wheel.x == 0.0f && wheel.y == 0.0f)
9143
540
        return;
9144
9145
    // Mouse wheel scrolling: find target and apply
9146
    // - don't renew lock if axis doesn't apply on the window.
9147
    // - select a main axis when both axises are being moved.
9148
62
    if (ImGuiWindow* window = (g.WheelingWindow ? g.WheelingWindow : FindBestWheelingWindow(wheel)))
9149
60
        if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
9150
60
        {
9151
60
            bool do_scroll[2] = { wheel.x != 0.0f && window->ScrollMax.x != 0.0f, wheel.y != 0.0f && window->ScrollMax.y != 0.0f };
9152
60
            if (do_scroll[ImGuiAxis_X] && do_scroll[ImGuiAxis_Y])
9153
7
                do_scroll[(g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? ImGuiAxis_Y : ImGuiAxis_X] = false;
9154
60
            if (do_scroll[ImGuiAxis_X])
9155
13
            {
9156
13
                LockWheelingWindow(window, wheel.x);
9157
13
                float max_step = window->InnerRect.GetWidth() * 0.67f;
9158
13
                float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
9159
13
                SetScrollX(window, window->Scroll.x - wheel.x * scroll_step);
9160
13
            }
9161
60
            if (do_scroll[ImGuiAxis_Y])
9162
8
            {
9163
8
                LockWheelingWindow(window, wheel.y);
9164
8
                float max_step = window->InnerRect.GetHeight() * 0.67f;
9165
8
                float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
9166
8
                SetScrollY(window, window->Scroll.y - wheel.y * scroll_step);
9167
8
            }
9168
60
        }
9169
62
}
9170
9171
void ImGui::SetNextFrameWantCaptureKeyboard(bool want_capture_keyboard)
9172
0
{
9173
0
    ImGuiContext& g = *GImGui;
9174
0
    g.WantCaptureKeyboardNextFrame = want_capture_keyboard ? 1 : 0;
9175
0
}
9176
9177
void ImGui::SetNextFrameWantCaptureMouse(bool want_capture_mouse)
9178
0
{
9179
0
    ImGuiContext& g = *GImGui;
9180
0
    g.WantCaptureMouseNextFrame = want_capture_mouse ? 1 : 0;
9181
0
}
9182
9183
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9184
static const char* GetInputSourceName(ImGuiInputSource source)
9185
0
{
9186
0
    const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" };
9187
0
    IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT && source >= 0 && source < ImGuiInputSource_COUNT);
9188
0
    return input_source_names[source];
9189
0
}
9190
static void DebugPrintInputEvent(const char* prefix, const ImGuiInputEvent* e)
9191
0
{
9192
0
    ImGuiContext& g = *GImGui;
9193
0
    if (e->Type == ImGuiInputEventType_MousePos)    { if (e->MousePos.PosX == -FLT_MAX && e->MousePos.PosY == -FLT_MAX) IMGUI_DEBUG_LOG_IO("%s: MousePos (-FLT_MAX, -FLT_MAX)\n", prefix); else IMGUI_DEBUG_LOG_IO("%s: MousePos (%.1f, %.1f)\n", prefix, e->MousePos.PosX, e->MousePos.PosY); return; }
9194
0
    if (e->Type == ImGuiInputEventType_MouseButton) { IMGUI_DEBUG_LOG_IO("%s: MouseButton %d %s\n", prefix, e->MouseButton.Button, e->MouseButton.Down ? "Down" : "Up"); return; }
9195
0
    if (e->Type == ImGuiInputEventType_MouseWheel)  { IMGUI_DEBUG_LOG_IO("%s: MouseWheel (%.3f, %.3f)\n", prefix, e->MouseWheel.WheelX, e->MouseWheel.WheelY); return; }
9196
0
    if (e->Type == ImGuiInputEventType_MouseViewport){IMGUI_DEBUG_LOG_IO("%s: MouseViewport (0x%08X)\n", prefix, e->MouseViewport.HoveredViewportID); return; }
9197
0
    if (e->Type == ImGuiInputEventType_Key)         { IMGUI_DEBUG_LOG_IO("%s: Key \"%s\" %s\n", prefix, ImGui::GetKeyName(e->Key.Key), e->Key.Down ? "Down" : "Up"); return; }
9198
0
    if (e->Type == ImGuiInputEventType_Text)        { IMGUI_DEBUG_LOG_IO("%s: Text: %c (U+%08X)\n", prefix, e->Text.Char, e->Text.Char); return; }
9199
0
    if (e->Type == ImGuiInputEventType_Focus)       { IMGUI_DEBUG_LOG_IO("%s: AppFocused %d\n", prefix, e->AppFocused.Focused); return; }
9200
0
}
9201
#endif
9202
9203
// Process input queue
9204
// We always call this with the value of 'bool g.IO.ConfigInputTrickleEventQueue'.
9205
// - trickle_fast_inputs = false : process all events, turn into flattened input state (e.g. successive down/up/down/up will be lost)
9206
// - trickle_fast_inputs = true  : process as many events as possible (successive down/up/down/up will be trickled over several frames so nothing is lost) (new feature in 1.87)
9207
void ImGui::UpdateInputEvents(bool trickle_fast_inputs)
9208
34.4k
{
9209
34.4k
    ImGuiContext& g = *GImGui;
9210
34.4k
    ImGuiIO& io = g.IO;
9211
9212
    // Only trickle chars<>key when working with InputText()
9213
    // FIXME: InputText() could parse event trail?
9214
    // FIXME: Could specialize chars<>keys trickling rules for control keys (those not typically associated to characters)
9215
34.4k
    const bool trickle_interleaved_keys_and_text = (trickle_fast_inputs && g.WantTextInputNextFrame == 1);
9216
9217
34.4k
    bool mouse_moved = false, mouse_wheeled = false, key_changed = false, text_inputted = false;
9218
34.4k
    int  mouse_button_changed = 0x00;
9219
34.4k
    ImBitArray<ImGuiKey_KeysData_SIZE> key_changed_mask;
9220
9221
34.4k
    int event_n = 0;
9222
45.5k
    for (; event_n < g.InputEventsQueue.Size; event_n++)
9223
13.8k
    {
9224
13.8k
        ImGuiInputEvent* e = &g.InputEventsQueue[event_n];
9225
13.8k
        if (e->Type == ImGuiInputEventType_MousePos)
9226
2.64k
        {
9227
            // Trickling Rule: Stop processing queued events if we already handled a mouse button change
9228
2.64k
            ImVec2 event_pos(e->MousePos.PosX, e->MousePos.PosY);
9229
2.64k
            if (trickle_fast_inputs && (mouse_button_changed != 0 || mouse_wheeled || key_changed || text_inputted))
9230
614
                break;
9231
2.03k
            io.MousePos = event_pos;
9232
2.03k
            mouse_moved = true;
9233
2.03k
        }
9234
11.2k
        else if (e->Type == ImGuiInputEventType_MouseButton)
9235
5.08k
        {
9236
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9237
5.08k
            const ImGuiMouseButton button = e->MouseButton.Button;
9238
5.08k
            IM_ASSERT(button >= 0 && button < ImGuiMouseButton_COUNT);
9239
5.08k
            if (trickle_fast_inputs && ((mouse_button_changed & (1 << button)) || mouse_wheeled))
9240
947
                break;
9241
4.13k
            io.MouseDown[button] = e->MouseButton.Down;
9242
4.13k
            mouse_button_changed |= (1 << button);
9243
4.13k
        }
9244
6.14k
        else if (e->Type == ImGuiInputEventType_MouseWheel)
9245
1.34k
        {
9246
            // Trickling Rule: Stop processing queued events if we got multiple action on the event
9247
1.34k
            if (trickle_fast_inputs && (mouse_moved || mouse_button_changed != 0))
9248
578
                break;
9249
763
            io.MouseWheelH += e->MouseWheel.WheelX;
9250
763
            io.MouseWheel += e->MouseWheel.WheelY;
9251
763
            mouse_wheeled = true;
9252
763
        }
9253
4.80k
        else if (e->Type == ImGuiInputEventType_MouseViewport)
9254
0
        {
9255
0
            io.MouseHoveredViewport = e->MouseViewport.HoveredViewportID;
9256
0
        }
9257
4.80k
        else if (e->Type == ImGuiInputEventType_Key)
9258
1.13k
        {
9259
            // Trickling Rule: Stop processing queued events if we got multiple action on the same button
9260
1.13k
            ImGuiKey key = e->Key.Key;
9261
1.13k
            IM_ASSERT(key != ImGuiKey_None);
9262
1.13k
            ImGuiKeyData* key_data = GetKeyData(key);
9263
1.13k
            const int key_data_index = (int)(key_data - g.IO.KeysData);
9264
1.13k
            if (trickle_fast_inputs && key_data->Down != e->Key.Down && (key_changed_mask.TestBit(key_data_index) || text_inputted || mouse_button_changed != 0))
9265
36
                break;
9266
1.09k
            key_data->Down = e->Key.Down;
9267
1.09k
            key_data->AnalogValue = e->Key.AnalogValue;
9268
1.09k
            key_changed = true;
9269
1.09k
            key_changed_mask.SetBit(key_data_index);
9270
9271
            // Allow legacy code using io.KeysDown[GetKeyIndex()] with new backends
9272
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9273
            io.KeysDown[key_data_index] = key_data->Down;
9274
            if (io.KeyMap[key_data_index] != -1)
9275
                io.KeysDown[io.KeyMap[key_data_index]] = key_data->Down;
9276
#endif
9277
1.09k
        }
9278
3.67k
        else if (e->Type == ImGuiInputEventType_Text)
9279
2.63k
        {
9280
            // Trickling Rule: Stop processing queued events if keys/mouse have been interacted with
9281
2.63k
            if (trickle_fast_inputs && ((key_changed && trickle_interleaved_keys_and_text) || mouse_button_changed != 0 || mouse_moved || mouse_wheeled))
9282
564
                break;
9283
2.06k
            unsigned int c = e->Text.Char;
9284
2.06k
            io.InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
9285
2.06k
            if (trickle_interleaved_keys_and_text)
9286
0
                text_inputted = true;
9287
2.06k
        }
9288
1.04k
        else if (e->Type == ImGuiInputEventType_Focus)
9289
1.04k
        {
9290
            // We intentionally overwrite this and process in NewFrame(), in order to give a chance
9291
            // to multi-viewports backends to queue AddFocusEvent(false) + AddFocusEvent(true) in same frame.
9292
1.04k
            const bool focus_lost = !e->AppFocused.Focused;
9293
1.04k
            io.AppFocusLost = focus_lost;
9294
1.04k
        }
9295
0
        else
9296
0
        {
9297
0
            IM_ASSERT(0 && "Unknown event!");
9298
0
        }
9299
13.8k
    }
9300
9301
    // Record trail (for domain-specific applications wanting to access a precise trail)
9302
    //if (event_n != 0) IMGUI_DEBUG_LOG_IO("Processed: %d / Remaining: %d\n", event_n, g.InputEventsQueue.Size - event_n);
9303
45.5k
    for (int n = 0; n < event_n; n++)
9304
11.1k
        g.InputEventsTrail.push_back(g.InputEventsQueue[n]);
9305
9306
    // [DEBUG]
9307
34.4k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9308
34.4k
    if (event_n != 0 && (g.DebugLogFlags & ImGuiDebugLogFlags_EventIO))
9309
0
        for (int n = 0; n < g.InputEventsQueue.Size; n++)
9310
0
            DebugPrintInputEvent(n < event_n ? "Processed" : "Remaining", &g.InputEventsQueue[n]);
9311
34.4k
#endif
9312
9313
    // Remaining events will be processed on the next frame
9314
34.4k
    if (event_n == g.InputEventsQueue.Size)
9315
31.7k
        g.InputEventsQueue.resize(0);
9316
2.73k
    else
9317
2.73k
        g.InputEventsQueue.erase(g.InputEventsQueue.Data, g.InputEventsQueue.Data + event_n);
9318
9319
    // Clear buttons state when focus is lost
9320
    // - this is useful so e.g. releasing Alt after focus loss on Alt-Tab doesn't trigger the Alt menu toggle.
9321
    // - we clear in EndFrame() and not now in order allow application/user code polling this flag
9322
    //   (e.g. custom backend may want to clear additional data, custom widgets may want to react with a "canceling" event).
9323
34.4k
    if (g.IO.AppFocusLost)
9324
746
        g.IO.ClearInputKeys();
9325
34.4k
}
9326
9327
ImGuiID ImGui::GetKeyOwner(ImGuiKey key)
9328
0
{
9329
0
    if (!IsNamedKeyOrModKey(key))
9330
0
        return ImGuiKeyOwner_None;
9331
9332
0
    ImGuiContext& g = *GImGui;
9333
0
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9334
0
    ImGuiID owner_id = owner_data->OwnerCurr;
9335
9336
0
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9337
0
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9338
0
            return ImGuiKeyOwner_None;
9339
9340
0
    return owner_id;
9341
0
}
9342
9343
// TestKeyOwner(..., ID)   : (owner == None || owner == ID)
9344
// TestKeyOwner(..., None) : (owner == None)
9345
// TestKeyOwner(..., Any)  : no owner test
9346
// All paths are also testing for key not being locked, for the rare cases that key have been locked with using ImGuiInputFlags_LockXXX flags.
9347
bool ImGui::TestKeyOwner(ImGuiKey key, ImGuiID owner_id)
9348
79.9k
{
9349
79.9k
    if (!IsNamedKeyOrModKey(key))
9350
0
        return true;
9351
9352
79.9k
    ImGuiContext& g = *GImGui;
9353
79.9k
    if (g.ActiveIdUsingAllKeyboardKeys && owner_id != g.ActiveId && owner_id != ImGuiKeyOwner_Any)
9354
234
        if (key >= ImGuiKey_Keyboard_BEGIN && key < ImGuiKey_Keyboard_END)
9355
0
            return false;
9356
9357
79.9k
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9358
79.9k
    if (owner_id == ImGuiKeyOwner_Any)
9359
10.0k
        return (owner_data->LockThisFrame == false);
9360
9361
    // Note: SetKeyOwner() sets OwnerCurr. It is not strictly required for most mouse routing overlap (because of ActiveId/HoveredId
9362
    // are acting as filter before this has a chance to filter), but sane as soon as user tries to look into things.
9363
    // Setting OwnerCurr in SetKeyOwner() is more consistent than testing OwnerNext here: would be inconsistent with getter and other functions.
9364
69.8k
    if (owner_data->OwnerCurr != owner_id)
9365
153
    {
9366
153
        if (owner_data->LockThisFrame)
9367
0
            return false;
9368
153
        if (owner_data->OwnerCurr != ImGuiKeyOwner_None)
9369
12
            return false;
9370
153
    }
9371
9372
69.8k
    return true;
9373
69.8k
}
9374
9375
// _LockXXX flags are useful to lock keys away from code which is not input-owner aware.
9376
// When using _LockXXX flags, you can use ImGuiKeyOwner_Any to lock keys from everyone.
9377
// - SetKeyOwner(..., None)              : clears owner
9378
// - SetKeyOwner(..., Any, !Lock)        : illegal (assert)
9379
// - SetKeyOwner(..., Any or None, Lock) : set lock
9380
void ImGui::SetKeyOwner(ImGuiKey key, ImGuiID owner_id, ImGuiInputFlags flags)
9381
157
{
9382
157
    IM_ASSERT(IsNamedKeyOrModKey(key) && (owner_id != ImGuiKeyOwner_Any || (flags & (ImGuiInputFlags_LockThisFrame | ImGuiInputFlags_LockUntilRelease)))); // Can only use _Any with _LockXXX flags (to eat a key away without an ID to retrieve it)
9383
157
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetKeyOwner) == 0); // Passing flags not supported by this function!
9384
9385
157
    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
9386
157
    owner_data->OwnerCurr = owner_data->OwnerNext = owner_id;
9387
9388
    // We cannot lock by default as it would likely break lots of legacy code.
9389
    // In the case of using LockUntilRelease while key is not down we still lock during the frame (no key_data->Down test)
9390
157
    owner_data->LockUntilRelease = (flags & ImGuiInputFlags_LockUntilRelease) != 0;
9391
157
    owner_data->LockThisFrame = (flags & ImGuiInputFlags_LockThisFrame) != 0 || (owner_data->LockUntilRelease);
9392
157
}
9393
9394
// This is more or less equivalent to:
9395
//   if (IsItemHovered() || IsItemActive())
9396
//       SetKeyOwner(key, GetItemID());
9397
// Extensive uses of that (e.g. many calls for a single item) may want to manually perform the tests once and then call SetKeyOwner() multiple times.
9398
// More advanced usage scenarios may want to call SetKeyOwner() manually based on different condition.
9399
// Worth noting is that only one item can be hovered and only one item can be active, therefore this usage pattern doesn't need to bother with routing and priority.
9400
void ImGui::SetItemKeyOwner(ImGuiKey key, ImGuiInputFlags flags)
9401
0
{
9402
0
    ImGuiContext& g = *GImGui;
9403
0
    ImGuiID id = g.LastItemData.ID;
9404
0
    if (id == 0 || (g.HoveredId != id && g.ActiveId != id))
9405
0
        return;
9406
0
    if ((flags & ImGuiInputFlags_CondMask_) == 0)
9407
0
        flags |= ImGuiInputFlags_CondDefault_;
9408
0
    if ((g.HoveredId == id && (flags & ImGuiInputFlags_CondHovered)) || (g.ActiveId == id && (flags & ImGuiInputFlags_CondActive)))
9409
0
    {
9410
0
        IM_ASSERT((flags & ~ImGuiInputFlags_SupportedBySetItemKeyOwner) == 0); // Passing flags not supported by this function!
9411
0
        SetKeyOwner(key, id, flags & ~ImGuiInputFlags_CondMask_);
9412
0
    }
9413
0
}
9414
9415
bool ImGui::Shortcut(ImGuiKeyChord key_chord, ImGuiID owner_id, ImGuiInputFlags flags)
9416
68.8k
{
9417
68.8k
    ImGuiContext& g = *GImGui;
9418
9419
    // When using (owner_id == 0/Any): SetShortcutRouting() will use CurrentFocusScopeId and filter with this, so IsKeyPressed() is fine with he 0/Any.
9420
68.8k
    if ((flags & ImGuiInputFlags_RouteMask_) == 0)
9421
68.8k
        flags |= ImGuiInputFlags_RouteFocused;
9422
68.8k
    if (!SetShortcutRouting(key_chord, owner_id, flags))
9423
0
        return false;
9424
9425
68.8k
    if (key_chord & ImGuiMod_Shortcut)
9426
0
        key_chord = ConvertShortcutMod(key_chord);
9427
68.8k
    ImGuiKey mods = (ImGuiKey)(key_chord & ImGuiMod_Mask_);
9428
68.8k
    if (g.IO.KeyMods != mods)
9429
68.8k
        return false;
9430
9431
    // Special storage location for mods
9432
0
    ImGuiKey key = (ImGuiKey)(key_chord & ~ImGuiMod_Mask_);
9433
0
    if (key == ImGuiKey_None)
9434
0
        key = ConvertSingleModFlagToKey(mods);
9435
9436
0
    if (!IsKeyPressed(key, owner_id, (flags & (ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateMask_))))
9437
0
        return false;
9438
0
    IM_ASSERT((flags & ~ImGuiInputFlags_SupportedByShortcut) == 0); // Passing flags not supported by this function!
9439
9440
0
    return true;
9441
0
}
9442
9443
9444
//-----------------------------------------------------------------------------
9445
// [SECTION] ERROR CHECKING
9446
//-----------------------------------------------------------------------------
9447
9448
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
9449
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
9450
// If this triggers you have an issue:
9451
// - Most commonly: mismatched headers and compiled code version.
9452
// - Or: mismatched configuration #define, compilation settings, packing pragma etc.
9453
//   The configuration settings mentioned in imconfig.h must be set for all compilation units involved with Dear ImGui,
9454
//   which is way it is required you put them in your imconfig file (and not just before including imgui.h).
9455
//   Otherwise it is possible that different compilation units would see different structure layout
9456
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
9457
1
{
9458
1
    bool error = false;
9459
1
    if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
9460
1
    if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
9461
1
    if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
9462
1
    if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
9463
1
    if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
9464
1
    if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
9465
1
    if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
9466
1
    return !error;
9467
1
}
9468
9469
// Until 1.89 (IMGUI_VERSION_NUM < 18814) it was legal to use SetCursorPos() to extend the boundary of a parent (e.g. window or table cell)
9470
// This is causing issues and ambiguity and we need to retire that.
9471
// See https://github.com/ocornut/imgui/issues/5548 for more details.
9472
// [Scenario 1]
9473
//  Previously this would make the window content size ~200x200:
9474
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + End();  // NOT OK
9475
//  Instead, please submit an item:
9476
//    Begin(...) + SetCursorScreenPos(GetCursorScreenPos() + ImVec2(200,200)) + Dummy(ImVec2(0,0)) + End(); // OK
9477
//  Alternative:
9478
//    Begin(...) + Dummy(ImVec2(200,200)) + End(); // OK
9479
// [Scenario 2]
9480
//  For reference this is one of the issue what we aim to fix with this change:
9481
//    BeginGroup() + SomeItem("foobar") + SetCursorScreenPos(GetCursorScreenPos()) + EndGroup()
9482
//  The previous logic made SetCursorScreenPos(GetCursorScreenPos()) have a side-effect! It would erroneously incorporate ItemSpacing.y after the item into content size, making the group taller!
9483
//  While this code is a little twisted, no-one would expect SetXXX(GetXXX()) to have a side-effect. Using vertical alignment patterns could trigger this issue.
9484
void ImGui::ErrorCheckUsingSetCursorPosToExtendParentBoundaries()
9485
0
{
9486
0
    ImGuiContext& g = *GImGui;
9487
0
    ImGuiWindow* window = g.CurrentWindow;
9488
0
    IM_ASSERT(window->DC.IsSetPos);
9489
0
    window->DC.IsSetPos = false;
9490
0
#ifdef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
9491
0
    if (window->DC.CursorPos.x <= window->DC.CursorMaxPos.x && window->DC.CursorPos.y <= window->DC.CursorMaxPos.y)
9492
0
        return;
9493
0
    if (window->SkipItems)
9494
0
        return;
9495
0
    IM_ASSERT(0 && "Code uses SetCursorPos()/SetCursorScreenPos() to extend window/parent boundaries. Please submit an item e.g. Dummy() to validate extent.");
9496
#else
9497
    window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9498
#endif
9499
0
}
9500
9501
static void ImGui::ErrorCheckNewFrameSanityChecks()
9502
34.4k
{
9503
34.4k
    ImGuiContext& g = *GImGui;
9504
9505
    // Check user IM_ASSERT macro
9506
    // (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
9507
    //  If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
9508
    //  This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
9509
    // #define IM_ASSERT(EXPR)   if (SomeCode(EXPR)) SomeMoreCode();                    // Wrong!
9510
    // #define IM_ASSERT(EXPR)   do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0)   // Correct!
9511
34.4k
    if (true) IM_ASSERT(1); else IM_ASSERT(0);
9512
9513
    // Emscripten backends are often imprecise in their submission of DeltaTime. (#6114, #3644)
9514
    // Ideally the Emscripten app/backend should aim to fix or smooth this value and avoid feeding zero, but we tolerate it.
9515
#ifdef __EMSCRIPTEN__
9516
    if (g.IO.DeltaTime <= 0.0f && g.FrameCount > 0)
9517
        g.IO.DeltaTime = 0.00001f;
9518
#endif
9519
9520
    // Check user data
9521
    // (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
9522
34.4k
    IM_ASSERT(g.Initialized);
9523
34.4k
    IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0)              && "Need a positive DeltaTime!");
9524
34.4k
    IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount)  && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
9525
34.4k
    IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f  && "Invalid DisplaySize value!");
9526
34.4k
    IM_ASSERT(g.IO.Fonts->IsBuilt()                                     && "Font Atlas not built! Make sure you called ImGui_ImplXXXX_NewFrame() function for renderer backend, which should call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8()");
9527
34.4k
    IM_ASSERT(g.Style.CurveTessellationTol > 0.0f                       && "Invalid style setting!");
9528
34.4k
    IM_ASSERT(g.Style.CircleTessellationMaxError > 0.0f                 && "Invalid style setting!");
9529
34.4k
    IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f            && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
9530
34.4k
    IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
9531
34.4k
    IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
9532
34.4k
    IM_ASSERT(g.Style.ColorButtonPosition == ImGuiDir_Left || g.Style.ColorButtonPosition == ImGuiDir_Right);
9533
#ifndef IMGUI_DISABLE_OBSOLETE_KEYIO
9534
    for (int n = ImGuiKey_NamedKey_BEGIN; n < ImGuiKey_COUNT; n++)
9535
        IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < ImGuiKey_LegacyNativeKey_END && "io.KeyMap[] contains an out of bound value (need to be 0..511, or -1 for unmapped key)");
9536
9537
    // Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only added in 1.60 WIP)
9538
    if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && g.IO.BackendUsingLegacyKeyArrays == 1)
9539
        IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
9540
#endif
9541
9542
    // Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
9543
34.4k
    if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
9544
1
        g.IO.ConfigWindowsResizeFromEdges = false;
9545
9546
    // Perform simple check: error if Docking or Viewport are enabled _exactly_ on frame 1 (instead of frame 0 or later), which is a common error leading to loss of .ini data.
9547
34.4k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_DockingEnable) == 0)
9548
34.4k
        IM_ASSERT(0 && "Please set DockingEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9549
34.4k
    if (g.FrameCount == 1 && (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) && (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
9550
34.4k
        IM_ASSERT(0 && "Please set ViewportsEnable before the first call to NewFrame()! Otherwise you will lose your .ini settings!");
9551
9552
    // Perform simple checks: multi-viewport and platform windows support
9553
34.4k
    if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
9554
1
    {
9555
1
        if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
9556
0
        {
9557
0
            IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
9558
0
            IM_ASSERT(g.PlatformIO.Platform_CreateWindow  != NULL && "Platform init didn't install handlers?");
9559
0
            IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
9560
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowPos  != NULL && "Platform init didn't install handlers?");
9561
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowPos  != NULL && "Platform init didn't install handlers?");
9562
0
            IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
9563
0
            IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
9564
0
            IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
9565
0
            IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
9566
0
            if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
9567
0
                IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
9568
0
        }
9569
1
        else
9570
1
        {
9571
            // Disable feature, our backends do not support it
9572
1
            g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
9573
1
        }
9574
9575
        // Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
9576
1
        for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
9577
0
        {
9578
0
            ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
9579
0
            IM_UNUSED(mon);
9580
0
            IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor main bounds not setup properly.");
9581
0
            IM_ASSERT(ImRect(mon.MainPos, mon.MainPos + mon.MainSize).Contains(ImRect(mon.WorkPos, mon.WorkPos + mon.WorkSize)) && "Monitor work bounds not setup properly. If you don't have work area information, just copy MainPos/MainSize into them.");
9582
0
            IM_ASSERT(mon.DpiScale != 0.0f);
9583
0
        }
9584
1
    }
9585
34.4k
}
9586
9587
static void ImGui::ErrorCheckEndFrameSanityChecks()
9588
34.4k
{
9589
34.4k
    ImGuiContext& g = *GImGui;
9590
9591
    // Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
9592
    // One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
9593
    // It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
9594
    // send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
9595
    // We silently accommodate for this case by ignoring the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
9596
    // while still correctly asserting on mid-frame key press events.
9597
34.4k
    const ImGuiKeyChord key_mods = GetMergedModsFromKeys();
9598
34.4k
    IM_ASSERT((key_mods == 0 || g.IO.KeyMods == key_mods) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
9599
34.4k
    IM_UNUSED(key_mods);
9600
9601
    // [EXPERIMENTAL] Recover from errors: You may call this yourself before EndFrame().
9602
    //ErrorCheckEndFrameRecover();
9603
9604
    // Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
9605
    // to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
9606
34.4k
    if (g.CurrentWindowStack.Size != 1)
9607
0
    {
9608
0
        if (g.CurrentWindowStack.Size > 1)
9609
0
        {
9610
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
9611
0
            while (g.CurrentWindowStack.Size > 1)
9612
0
                End();
9613
0
        }
9614
0
        else
9615
0
        {
9616
0
            IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
9617
0
        }
9618
0
    }
9619
9620
34.4k
    IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
9621
34.4k
}
9622
9623
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
9624
// Must be called during or before EndFrame().
9625
// This is generally flawed as we are not necessarily End/Popping things in the right order.
9626
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
9627
// FIXME: Can't recover from interleaved BeginTabBar/Begin
9628
void    ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9629
0
{
9630
    // PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
9631
0
    ImGuiContext& g = *GImGui;
9632
0
    while (g.CurrentWindowStack.Size > 0) //-V1044
9633
0
    {
9634
0
        ErrorCheckEndWindowRecover(log_callback, user_data);
9635
0
        ImGuiWindow* window = g.CurrentWindow;
9636
0
        if (g.CurrentWindowStack.Size == 1)
9637
0
        {
9638
0
            IM_ASSERT(window->IsFallbackWindow);
9639
0
            break;
9640
0
        }
9641
0
        if (window->Flags & ImGuiWindowFlags_ChildWindow)
9642
0
        {
9643
0
            if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
9644
0
            EndChild();
9645
0
        }
9646
0
        else
9647
0
        {
9648
0
            if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
9649
0
            End();
9650
0
        }
9651
0
    }
9652
0
}
9653
9654
// Must be called before End()/EndChild()
9655
void    ImGui::ErrorCheckEndWindowRecover(ImGuiErrorLogCallback log_callback, void* user_data)
9656
0
{
9657
0
    ImGuiContext& g = *GImGui;
9658
0
    while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
9659
0
    {
9660
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
9661
0
        EndTable();
9662
0
    }
9663
9664
0
    ImGuiWindow* window = g.CurrentWindow;
9665
0
    ImGuiStackSizes* stack_sizes = &g.CurrentWindowStack.back().StackSizesOnBegin;
9666
0
    IM_ASSERT(window != NULL);
9667
0
    while (g.CurrentTabBar != NULL) //-V1044
9668
0
    {
9669
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
9670
0
        EndTabBar();
9671
0
    }
9672
0
    while (window->DC.TreeDepth > 0)
9673
0
    {
9674
0
        if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
9675
0
        TreePop();
9676
0
    }
9677
0
    while (g.GroupStack.Size > stack_sizes->SizeOfGroupStack) //-V1044
9678
0
    {
9679
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
9680
0
        EndGroup();
9681
0
    }
9682
0
    while (window->IDStack.Size > 1)
9683
0
    {
9684
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
9685
0
        PopID();
9686
0
    }
9687
0
    while (g.DisabledStackSize > stack_sizes->SizeOfDisabledStack) //-V1044
9688
0
    {
9689
0
        if (log_callback) log_callback(user_data, "Recovered from missing EndDisabled() in '%s'", window->Name);
9690
0
        EndDisabled();
9691
0
    }
9692
0
    while (g.ColorStack.Size > stack_sizes->SizeOfColorStack)
9693
0
    {
9694
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
9695
0
        PopStyleColor();
9696
0
    }
9697
0
    while (g.ItemFlagsStack.Size > stack_sizes->SizeOfItemFlagsStack) //-V1044
9698
0
    {
9699
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopItemFlag() in '%s'", window->Name);
9700
0
        PopItemFlag();
9701
0
    }
9702
0
    while (g.StyleVarStack.Size > stack_sizes->SizeOfStyleVarStack) //-V1044
9703
0
    {
9704
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
9705
0
        PopStyleVar();
9706
0
    }
9707
0
    while (g.FocusScopeStack.Size > stack_sizes->SizeOfFocusScopeStack + 1) //-V1044
9708
0
    {
9709
0
        if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
9710
0
        PopFocusScope();
9711
0
    }
9712
0
}
9713
9714
// Save current stack sizes for later compare
9715
void ImGuiStackSizes::SetToCurrentState()
9716
71.9k
{
9717
71.9k
    ImGuiContext& g = *GImGui;
9718
71.9k
    ImGuiWindow* window = g.CurrentWindow;
9719
71.9k
    SizeOfIDStack = (short)window->IDStack.Size;
9720
71.9k
    SizeOfColorStack = (short)g.ColorStack.Size;
9721
71.9k
    SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
9722
71.9k
    SizeOfFontStack = (short)g.FontStack.Size;
9723
71.9k
    SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
9724
71.9k
    SizeOfGroupStack = (short)g.GroupStack.Size;
9725
71.9k
    SizeOfItemFlagsStack = (short)g.ItemFlagsStack.Size;
9726
71.9k
    SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
9727
71.9k
    SizeOfDisabledStack = (short)g.DisabledStackSize;
9728
71.9k
}
9729
9730
// Compare to detect usage errors
9731
void ImGuiStackSizes::CompareWithCurrentState()
9732
71.9k
{
9733
71.9k
    ImGuiContext& g = *GImGui;
9734
71.9k
    ImGuiWindow* window = g.CurrentWindow;
9735
71.9k
    IM_UNUSED(window);
9736
9737
    // Window stacks
9738
    // NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
9739
71.9k
    IM_ASSERT(SizeOfIDStack         == window->IDStack.Size     && "PushID/PopID or TreeNode/TreePop Mismatch!");
9740
9741
    // Global stacks
9742
    // For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
9743
71.9k
    IM_ASSERT(SizeOfGroupStack      == g.GroupStack.Size        && "BeginGroup/EndGroup Mismatch!");
9744
71.9k
    IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size   && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
9745
71.9k
    IM_ASSERT(SizeOfDisabledStack   == g.DisabledStackSize      && "BeginDisabled/EndDisabled Mismatch!");
9746
71.9k
    IM_ASSERT(SizeOfItemFlagsStack  >= g.ItemFlagsStack.Size    && "PushItemFlag/PopItemFlag Mismatch!");
9747
71.9k
    IM_ASSERT(SizeOfColorStack      >= g.ColorStack.Size        && "PushStyleColor/PopStyleColor Mismatch!");
9748
71.9k
    IM_ASSERT(SizeOfStyleVarStack   >= g.StyleVarStack.Size     && "PushStyleVar/PopStyleVar Mismatch!");
9749
71.9k
    IM_ASSERT(SizeOfFontStack       >= g.FontStack.Size         && "PushFont/PopFont Mismatch!");
9750
71.9k
    IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size   && "PushFocusScope/PopFocusScope Mismatch!");
9751
71.9k
}
9752
9753
9754
//-----------------------------------------------------------------------------
9755
// [SECTION] LAYOUT
9756
//-----------------------------------------------------------------------------
9757
// - ItemSize()
9758
// - ItemAdd()
9759
// - SameLine()
9760
// - GetCursorScreenPos()
9761
// - SetCursorScreenPos()
9762
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
9763
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
9764
// - GetCursorStartPos()
9765
// - Indent()
9766
// - Unindent()
9767
// - SetNextItemWidth()
9768
// - PushItemWidth()
9769
// - PushMultiItemsWidths()
9770
// - PopItemWidth()
9771
// - CalcItemWidth()
9772
// - CalcItemSize()
9773
// - GetTextLineHeight()
9774
// - GetTextLineHeightWithSpacing()
9775
// - GetFrameHeight()
9776
// - GetFrameHeightWithSpacing()
9777
// - GetContentRegionMax()
9778
// - GetContentRegionMaxAbs() [Internal]
9779
// - GetContentRegionAvail(),
9780
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
9781
// - BeginGroup()
9782
// - EndGroup()
9783
// Also see in imgui_widgets: tab bars, and in imgui_tables: tables, columns.
9784
//-----------------------------------------------------------------------------
9785
9786
// Advance cursor given item size for layout.
9787
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
9788
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
9789
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
9790
5.33k
{
9791
5.33k
    ImGuiContext& g = *GImGui;
9792
5.33k
    ImGuiWindow* window = g.CurrentWindow;
9793
5.33k
    if (window->SkipItems)
9794
0
        return;
9795
9796
    // We increase the height in this function to accommodate for baseline offset.
9797
    // In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
9798
    // but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
9799
5.33k
    const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
9800
9801
5.33k
    const float line_y1 = window->DC.IsSameLine ? window->DC.CursorPosPrevLine.y : window->DC.CursorPos.y;
9802
5.33k
    const float line_height = ImMax(window->DC.CurrLineSize.y, /*ImMax(*/window->DC.CursorPos.y - line_y1/*, 0.0f)*/ + size.y + offset_to_match_baseline_y);
9803
9804
    // Always align ourselves on pixel boundaries
9805
    //if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
9806
5.33k
    window->DC.CursorPosPrevLine.x = window->DC.CursorPos.x + size.x;
9807
5.33k
    window->DC.CursorPosPrevLine.y = line_y1;
9808
5.33k
    window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);    // Next line
9809
5.33k
    window->DC.CursorPos.y = IM_FLOOR(line_y1 + line_height + g.Style.ItemSpacing.y);                       // Next line
9810
5.33k
    window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
9811
5.33k
    window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
9812
    //if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
9813
9814
5.33k
    window->DC.PrevLineSize.y = line_height;
9815
5.33k
    window->DC.CurrLineSize.y = 0.0f;
9816
5.33k
    window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
9817
5.33k
    window->DC.CurrLineTextBaseOffset = 0.0f;
9818
5.33k
    window->DC.IsSameLine = window->DC.IsSetPos = false;
9819
9820
    // Horizontal layout mode
9821
5.33k
    if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
9822
0
        SameLine();
9823
5.33k
}
9824
9825
// Declare item bounding box for clipping and interaction.
9826
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
9827
// declare their minimum size requirement to ItemSize() and provide a larger region to ItemAdd() which is used drawing/interaction.
9828
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemFlags extra_flags)
9829
80.5k
{
9830
80.5k
    ImGuiContext& g = *GImGui;
9831
80.5k
    ImGuiWindow* window = g.CurrentWindow;
9832
9833
    // Set item data
9834
    // (DisplayRect is left untouched, made valid when ImGuiItemStatusFlags_HasDisplayRect is set)
9835
80.5k
    g.LastItemData.ID = id;
9836
80.5k
    g.LastItemData.Rect = bb;
9837
80.5k
    g.LastItemData.NavRect = nav_bb_arg ? *nav_bb_arg : bb;
9838
80.5k
    g.LastItemData.InFlags = g.CurrentItemFlags | extra_flags;
9839
80.5k
    g.LastItemData.StatusFlags = ImGuiItemStatusFlags_None;
9840
9841
    // Directional navigation processing
9842
80.5k
    if (id != 0)
9843
76.9k
    {
9844
76.9k
        KeepAliveID(id);
9845
9846
        // Runs prior to clipping early-out
9847
        //  (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
9848
        //  (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests
9849
        //      unfortunately, but it is still limited to one window. It may not scale very well for windows with ten of
9850
        //      thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
9851
        //      We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able
9852
        //      to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick).
9853
        // We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
9854
        // If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
9855
76.9k
        if (!(g.LastItemData.InFlags & ImGuiItemFlags_NoNav))
9856
70.5k
        {
9857
70.5k
            window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
9858
70.5k
            if (g.NavId == id || g.NavAnyRequest)
9859
375
                if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
9860
326
                    if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
9861
326
                        NavProcessItem();
9862
70.5k
        }
9863
9864
        // [DEBUG] People keep stumbling on this problem and using "" as identifier in the root of a window instead of "##something".
9865
        // Empty identifier are valid and useful in a small amount of cases, but 99.9% of the time you want to use "##something".
9866
        // READ THE FAQ: https://dearimgui.org/faq
9867
76.9k
        IM_ASSERT(id != window->ID && "Cannot have an empty ID at the root of a window. If you need an empty label, use ## and read the FAQ about how the ID Stack works!");
9868
76.9k
    }
9869
80.5k
    g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
9870
9871
#ifdef IMGUI_ENABLE_TEST_ENGINE
9872
    if (id != 0)
9873
        IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
9874
#endif
9875
9876
    // Clipping test
9877
    // (FIXME: This is a modified copy of IsClippedEx() so we can reuse the is_rect_visible value)
9878
    //const bool is_clipped = IsClippedEx(bb, id);
9879
    //if (is_clipped)
9880
    //    return false;
9881
80.5k
    const bool is_rect_visible = bb.Overlaps(window->ClipRect);
9882
80.5k
    if (!is_rect_visible)
9883
2.80k
        if (id == 0 || (id != g.ActiveId && id != g.NavId))
9884
2.74k
            if (!g.LogEnabled)
9885
2.74k
                return false;
9886
9887
    // [DEBUG]
9888
77.8k
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
9889
77.8k
    if (id != 0 && id == g.DebugLocateId)
9890
0
        DebugLocateItemResolveWithLastItem();
9891
77.8k
#endif
9892
    //if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
9893
9894
    // We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
9895
77.8k
    if (is_rect_visible)
9896
77.7k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Visible;
9897
77.8k
    if (IsMouseHoveringRect(bb.Min, bb.Max))
9898
2.58k
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredRect;
9899
77.8k
    return true;
9900
80.5k
}
9901
9902
// Gets back to previous line and continue with horizontal layout
9903
//      offset_from_start_x == 0 : follow right after previous item
9904
//      offset_from_start_x != 0 : align to specified x position (relative to window/group left)
9905
//      spacing_w < 0            : use default spacing if pos_x == 0, no spacing if pos_x != 0
9906
//      spacing_w >= 0           : enforce spacing amount
9907
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
9908
0
{
9909
0
    ImGuiContext& g = *GImGui;
9910
0
    ImGuiWindow* window = g.CurrentWindow;
9911
0
    if (window->SkipItems)
9912
0
        return;
9913
9914
0
    if (offset_from_start_x != 0.0f)
9915
0
    {
9916
0
        if (spacing_w < 0.0f)
9917
0
            spacing_w = 0.0f;
9918
0
        window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
9919
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9920
0
    }
9921
0
    else
9922
0
    {
9923
0
        if (spacing_w < 0.0f)
9924
0
            spacing_w = g.Style.ItemSpacing.x;
9925
0
        window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
9926
0
        window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
9927
0
    }
9928
0
    window->DC.CurrLineSize = window->DC.PrevLineSize;
9929
0
    window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
9930
0
    window->DC.IsSameLine = true;
9931
0
}
9932
9933
ImVec2 ImGui::GetCursorScreenPos()
9934
4.01k
{
9935
4.01k
    ImGuiWindow* window = GetCurrentWindowRead();
9936
4.01k
    return window->DC.CursorPos;
9937
4.01k
}
9938
9939
// 2022/08/05: Setting cursor position also extend boundaries (via modifying CursorMaxPos) used to compute window size, group size etc.
9940
// I believe this was is a judicious choice but it's probably being relied upon (it has been the case since 1.31 and 1.50)
9941
// It would be sane if we requested user to use SetCursorPos() + Dummy(ImVec2(0,0)) to extend CursorMaxPos...
9942
void ImGui::SetCursorScreenPos(const ImVec2& pos)
9943
0
{
9944
0
    ImGuiWindow* window = GetCurrentWindow();
9945
0
    window->DC.CursorPos = pos;
9946
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9947
0
    window->DC.IsSetPos = true;
9948
0
}
9949
9950
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
9951
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
9952
ImVec2 ImGui::GetCursorPos()
9953
0
{
9954
0
    ImGuiWindow* window = GetCurrentWindowRead();
9955
0
    return window->DC.CursorPos - window->Pos + window->Scroll;
9956
0
}
9957
9958
float ImGui::GetCursorPosX()
9959
0
{
9960
0
    ImGuiWindow* window = GetCurrentWindowRead();
9961
0
    return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
9962
0
}
9963
9964
float ImGui::GetCursorPosY()
9965
0
{
9966
0
    ImGuiWindow* window = GetCurrentWindowRead();
9967
0
    return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
9968
0
}
9969
9970
void ImGui::SetCursorPos(const ImVec2& local_pos)
9971
0
{
9972
0
    ImGuiWindow* window = GetCurrentWindow();
9973
0
    window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
9974
    //window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
9975
0
    window->DC.IsSetPos = true;
9976
0
}
9977
9978
void ImGui::SetCursorPosX(float x)
9979
0
{
9980
0
    ImGuiWindow* window = GetCurrentWindow();
9981
0
    window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
9982
    //window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
9983
0
    window->DC.IsSetPos = true;
9984
0
}
9985
9986
void ImGui::SetCursorPosY(float y)
9987
0
{
9988
0
    ImGuiWindow* window = GetCurrentWindow();
9989
0
    window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
9990
    //window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
9991
0
    window->DC.IsSetPos = true;
9992
0
}
9993
9994
ImVec2 ImGui::GetCursorStartPos()
9995
0
{
9996
0
    ImGuiWindow* window = GetCurrentWindowRead();
9997
0
    return window->DC.CursorStartPos - window->Pos;
9998
0
}
9999
10000
void ImGui::Indent(float indent_w)
10001
0
{
10002
0
    ImGuiContext& g = *GImGui;
10003
0
    ImGuiWindow* window = GetCurrentWindow();
10004
0
    window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10005
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10006
0
}
10007
10008
void ImGui::Unindent(float indent_w)
10009
0
{
10010
0
    ImGuiContext& g = *GImGui;
10011
0
    ImGuiWindow* window = GetCurrentWindow();
10012
0
    window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
10013
0
    window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
10014
0
}
10015
10016
// Affect large frame+labels widgets only.
10017
void ImGui::SetNextItemWidth(float item_width)
10018
0
{
10019
0
    ImGuiContext& g = *GImGui;
10020
0
    g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
10021
0
    g.NextItemData.Width = item_width;
10022
0
}
10023
10024
// FIXME: Remove the == 0.0f behavior?
10025
void ImGui::PushItemWidth(float item_width)
10026
0
{
10027
0
    ImGuiContext& g = *GImGui;
10028
0
    ImGuiWindow* window = g.CurrentWindow;
10029
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10030
0
    window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
10031
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10032
0
}
10033
10034
void ImGui::PushMultiItemsWidths(int components, float w_full)
10035
0
{
10036
0
    ImGuiContext& g = *GImGui;
10037
0
    ImGuiWindow* window = g.CurrentWindow;
10038
0
    const ImGuiStyle& style = g.Style;
10039
0
    const float w_item_one  = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
10040
0
    const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
10041
0
    window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
10042
0
    window->DC.ItemWidthStack.push_back(w_item_last);
10043
0
    for (int i = 0; i < components - 2; i++)
10044
0
        window->DC.ItemWidthStack.push_back(w_item_one);
10045
0
    window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
10046
0
    g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
10047
0
}
10048
10049
void ImGui::PopItemWidth()
10050
0
{
10051
0
    ImGuiWindow* window = GetCurrentWindow();
10052
0
    window->DC.ItemWidth = window->DC.ItemWidthStack.back();
10053
0
    window->DC.ItemWidthStack.pop_back();
10054
0
}
10055
10056
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
10057
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
10058
float ImGui::CalcItemWidth()
10059
0
{
10060
0
    ImGuiContext& g = *GImGui;
10061
0
    ImGuiWindow* window = g.CurrentWindow;
10062
0
    float w;
10063
0
    if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
10064
0
        w = g.NextItemData.Width;
10065
0
    else
10066
0
        w = window->DC.ItemWidth;
10067
0
    if (w < 0.0f)
10068
0
    {
10069
0
        float region_max_x = GetContentRegionMaxAbs().x;
10070
0
        w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
10071
0
    }
10072
0
    w = IM_FLOOR(w);
10073
0
    return w;
10074
0
}
10075
10076
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
10077
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
10078
// Note that only CalcItemWidth() is publicly exposed.
10079
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
10080
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
10081
0
{
10082
0
    ImGuiContext& g = *GImGui;
10083
0
    ImGuiWindow* window = g.CurrentWindow;
10084
10085
0
    ImVec2 region_max;
10086
0
    if (size.x < 0.0f || size.y < 0.0f)
10087
0
        region_max = GetContentRegionMaxAbs();
10088
10089
0
    if (size.x == 0.0f)
10090
0
        size.x = default_w;
10091
0
    else if (size.x < 0.0f)
10092
0
        size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
10093
10094
0
    if (size.y == 0.0f)
10095
0
        size.y = default_h;
10096
0
    else if (size.y < 0.0f)
10097
0
        size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
10098
10099
0
    return size;
10100
0
}
10101
10102
float ImGui::GetTextLineHeight()
10103
0
{
10104
0
    ImGuiContext& g = *GImGui;
10105
0
    return g.FontSize;
10106
0
}
10107
10108
float ImGui::GetTextLineHeightWithSpacing()
10109
3.02k
{
10110
3.02k
    ImGuiContext& g = *GImGui;
10111
3.02k
    return g.FontSize + g.Style.ItemSpacing.y;
10112
3.02k
}
10113
10114
float ImGui::GetFrameHeight()
10115
124
{
10116
124
    ImGuiContext& g = *GImGui;
10117
124
    return g.FontSize + g.Style.FramePadding.y * 2.0f;
10118
124
}
10119
10120
float ImGui::GetFrameHeightWithSpacing()
10121
0
{
10122
0
    ImGuiContext& g = *GImGui;
10123
0
    return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
10124
0
}
10125
10126
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
10127
10128
// FIXME: This is in window space (not screen space!).
10129
ImVec2 ImGui::GetContentRegionMax()
10130
0
{
10131
0
    ImGuiContext& g = *GImGui;
10132
0
    ImGuiWindow* window = g.CurrentWindow;
10133
0
    ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
10134
0
    if (window->DC.CurrentColumns || g.CurrentTable)
10135
0
        mx.x = window->WorkRect.Max.x - window->Pos.x;
10136
0
    return mx;
10137
0
}
10138
10139
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
10140
ImVec2 ImGui::GetContentRegionMaxAbs()
10141
3.02k
{
10142
3.02k
    ImGuiContext& g = *GImGui;
10143
3.02k
    ImGuiWindow* window = g.CurrentWindow;
10144
3.02k
    ImVec2 mx = window->ContentRegionRect.Max;
10145
3.02k
    if (window->DC.CurrentColumns || g.CurrentTable)
10146
0
        mx.x = window->WorkRect.Max.x;
10147
3.02k
    return mx;
10148
3.02k
}
10149
10150
ImVec2 ImGui::GetContentRegionAvail()
10151
3.02k
{
10152
3.02k
    ImGuiWindow* window = GImGui->CurrentWindow;
10153
3.02k
    return GetContentRegionMaxAbs() - window->DC.CursorPos;
10154
3.02k
}
10155
10156
// In window space (not screen space!)
10157
ImVec2 ImGui::GetWindowContentRegionMin()
10158
0
{
10159
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10160
0
    return window->ContentRegionRect.Min - window->Pos;
10161
0
}
10162
10163
ImVec2 ImGui::GetWindowContentRegionMax()
10164
3.02k
{
10165
3.02k
    ImGuiWindow* window = GImGui->CurrentWindow;
10166
3.02k
    return window->ContentRegionRect.Max - window->Pos;
10167
3.02k
}
10168
10169
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
10170
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
10171
// FIXME-OPT: Could we safely early out on ->SkipItems?
10172
void ImGui::BeginGroup()
10173
0
{
10174
0
    ImGuiContext& g = *GImGui;
10175
0
    ImGuiWindow* window = g.CurrentWindow;
10176
10177
0
    g.GroupStack.resize(g.GroupStack.Size + 1);
10178
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10179
0
    group_data.WindowID = window->ID;
10180
0
    group_data.BackupCursorPos = window->DC.CursorPos;
10181
0
    group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
10182
0
    group_data.BackupIndent = window->DC.Indent;
10183
0
    group_data.BackupGroupOffset = window->DC.GroupOffset;
10184
0
    group_data.BackupCurrLineSize = window->DC.CurrLineSize;
10185
0
    group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
10186
0
    group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
10187
0
    group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
10188
0
    group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
10189
0
    group_data.EmitItem = true;
10190
10191
0
    window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
10192
0
    window->DC.Indent = window->DC.GroupOffset;
10193
0
    window->DC.CursorMaxPos = window->DC.CursorPos;
10194
0
    window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
10195
0
    if (g.LogEnabled)
10196
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10197
0
}
10198
10199
void ImGui::EndGroup()
10200
0
{
10201
0
    ImGuiContext& g = *GImGui;
10202
0
    ImGuiWindow* window = g.CurrentWindow;
10203
0
    IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
10204
10205
0
    ImGuiGroupData& group_data = g.GroupStack.back();
10206
0
    IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
10207
10208
0
    if (window->DC.IsSetPos)
10209
0
        ErrorCheckUsingSetCursorPosToExtendParentBoundaries();
10210
10211
0
    ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
10212
10213
0
    window->DC.CursorPos = group_data.BackupCursorPos;
10214
0
    window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
10215
0
    window->DC.Indent = group_data.BackupIndent;
10216
0
    window->DC.GroupOffset = group_data.BackupGroupOffset;
10217
0
    window->DC.CurrLineSize = group_data.BackupCurrLineSize;
10218
0
    window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
10219
0
    if (g.LogEnabled)
10220
0
        g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
10221
10222
0
    if (!group_data.EmitItem)
10223
0
    {
10224
0
        g.GroupStack.pop_back();
10225
0
        return;
10226
0
    }
10227
10228
0
    window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset);      // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
10229
0
    ItemSize(group_bb.GetSize());
10230
0
    ItemAdd(group_bb, 0, NULL, ImGuiItemFlags_NoTabStop);
10231
10232
    // If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
10233
    // It would be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
10234
    // Also if you grep for LastItemId you'll notice it is only used in that context.
10235
    // (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
10236
0
    const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
10237
0
    const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
10238
0
    if (group_contains_curr_active_id)
10239
0
        g.LastItemData.ID = g.ActiveId;
10240
0
    else if (group_contains_prev_active_id)
10241
0
        g.LastItemData.ID = g.ActiveIdPreviousFrame;
10242
0
    g.LastItemData.Rect = group_bb;
10243
10244
    // Forward Hovered flag
10245
0
    const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
10246
0
    if (group_contains_curr_hovered_id)
10247
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
10248
10249
    // Forward Edited flag
10250
0
    if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
10251
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Edited;
10252
10253
    // Forward Deactivated flag
10254
0
    g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
10255
0
    if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
10256
0
        g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_Deactivated;
10257
10258
0
    g.GroupStack.pop_back();
10259
    //window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255));   // [Debug]
10260
0
}
10261
10262
10263
//-----------------------------------------------------------------------------
10264
// [SECTION] SCROLLING
10265
//-----------------------------------------------------------------------------
10266
10267
// Helper to snap on edges when aiming at an item very close to the edge,
10268
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
10269
// When we refactor the scrolling API this may be configurable with a flag?
10270
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
10271
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
10272
0
{
10273
0
    if (target <= snap_min + snap_threshold)
10274
0
        return ImLerp(snap_min, target, center_ratio);
10275
0
    if (target >= snap_max - snap_threshold)
10276
0
        return ImLerp(target, snap_max, center_ratio);
10277
0
    return target;
10278
0
}
10279
10280
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
10281
71.9k
{
10282
71.9k
    ImVec2 scroll = window->Scroll;
10283
71.9k
    ImVec2 decoration_size(window->DecoOuterSizeX1 + window->DecoInnerSizeX1 + window->DecoOuterSizeX2, window->DecoOuterSizeY1 + window->DecoInnerSizeY1 + window->DecoOuterSizeY2);
10284
215k
    for (int axis = 0; axis < 2; axis++)
10285
143k
    {
10286
143k
        if (window->ScrollTarget[axis] < FLT_MAX)
10287
1.94k
        {
10288
1.94k
            float center_ratio = window->ScrollTargetCenterRatio[axis];
10289
1.94k
            float scroll_target = window->ScrollTarget[axis];
10290
1.94k
            if (window->ScrollTargetEdgeSnapDist[axis] > 0.0f)
10291
0
            {
10292
0
                float snap_min = 0.0f;
10293
0
                float snap_max = window->ScrollMax[axis] + window->SizeFull[axis] - decoration_size[axis];
10294
0
                scroll_target = CalcScrollEdgeSnap(scroll_target, snap_min, snap_max, window->ScrollTargetEdgeSnapDist[axis], center_ratio);
10295
0
            }
10296
1.94k
            scroll[axis] = scroll_target - center_ratio * (window->SizeFull[axis] - decoration_size[axis]);
10297
1.94k
        }
10298
143k
        scroll[axis] = IM_FLOOR(ImMax(scroll[axis], 0.0f));
10299
143k
        if (!window->Collapsed && !window->SkipItems)
10300
79.5k
            scroll[axis] = ImMin(scroll[axis], window->ScrollMax[axis]);
10301
143k
    }
10302
71.9k
    return scroll;
10303
71.9k
}
10304
10305
void ImGui::ScrollToItem(ImGuiScrollFlags flags)
10306
0
{
10307
0
    ImGuiContext& g = *GImGui;
10308
0
    ImGuiWindow* window = g.CurrentWindow;
10309
0
    ScrollToRectEx(window, g.LastItemData.NavRect, flags);
10310
0
}
10311
10312
void ImGui::ScrollToRect(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10313
0
{
10314
0
    ScrollToRectEx(window, item_rect, flags);
10315
0
}
10316
10317
// Scroll to keep newly navigated item fully into view
10318
ImVec2 ImGui::ScrollToRectEx(ImGuiWindow* window, const ImRect& item_rect, ImGuiScrollFlags flags)
10319
5
{
10320
5
    ImGuiContext& g = *GImGui;
10321
5
    ImRect scroll_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
10322
5
    scroll_rect.Min.x = ImMin(scroll_rect.Min.x + window->DecoInnerSizeX1, scroll_rect.Max.x);
10323
5
    scroll_rect.Min.y = ImMin(scroll_rect.Min.y + window->DecoInnerSizeY1, scroll_rect.Max.y);
10324
    //GetForegroundDrawList(window)->AddRect(item_rect.Min, item_rect.Max, IM_COL32(255,0,0,255), 0.0f, 0, 5.0f); // [DEBUG]
10325
    //GetForegroundDrawList(window)->AddRect(scroll_rect.Min, scroll_rect.Max, IM_COL32_WHITE); // [DEBUG]
10326
10327
    // Check that only one behavior is selected per axis
10328
5
    IM_ASSERT((flags & ImGuiScrollFlags_MaskX_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskX_));
10329
5
    IM_ASSERT((flags & ImGuiScrollFlags_MaskY_) == 0 || ImIsPowerOfTwo(flags & ImGuiScrollFlags_MaskY_));
10330
10331
    // Defaults
10332
5
    ImGuiScrollFlags in_flags = flags;
10333
5
    if ((flags & ImGuiScrollFlags_MaskX_) == 0 && window->ScrollbarX)
10334
0
        flags |= ImGuiScrollFlags_KeepVisibleEdgeX;
10335
5
    if ((flags & ImGuiScrollFlags_MaskY_) == 0)
10336
5
        flags |= window->Appearing ? ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeY;
10337
10338
5
    const bool fully_visible_x = item_rect.Min.x >= scroll_rect.Min.x && item_rect.Max.x <= scroll_rect.Max.x;
10339
5
    const bool fully_visible_y = item_rect.Min.y >= scroll_rect.Min.y && item_rect.Max.y <= scroll_rect.Max.y;
10340
5
    const bool can_be_fully_visible_x = (item_rect.GetWidth() + g.Style.ItemSpacing.x * 2.0f) <= scroll_rect.GetWidth() || (window->AutoFitFramesX > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10341
5
    const bool can_be_fully_visible_y = (item_rect.GetHeight() + g.Style.ItemSpacing.y * 2.0f) <= scroll_rect.GetHeight() || (window->AutoFitFramesY > 0) || (window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0;
10342
10343
5
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeX) && !fully_visible_x)
10344
0
    {
10345
0
        if (item_rect.Min.x < scroll_rect.Min.x || !can_be_fully_visible_x)
10346
0
            SetScrollFromPosX(window, item_rect.Min.x - g.Style.ItemSpacing.x - window->Pos.x, 0.0f);
10347
0
        else if (item_rect.Max.x >= scroll_rect.Max.x)
10348
0
            SetScrollFromPosX(window, item_rect.Max.x + g.Style.ItemSpacing.x - window->Pos.x, 1.0f);
10349
0
    }
10350
5
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterX) && !fully_visible_x) || (flags & ImGuiScrollFlags_AlwaysCenterX))
10351
0
    {
10352
0
        if (can_be_fully_visible_x)
10353
0
            SetScrollFromPosX(window, ImFloor((item_rect.Min.x + item_rect.Max.x) * 0.5f) - window->Pos.x, 0.5f);
10354
0
        else
10355
0
            SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x, 0.0f);
10356
0
    }
10357
10358
5
    if ((flags & ImGuiScrollFlags_KeepVisibleEdgeY) && !fully_visible_y)
10359
0
    {
10360
0
        if (item_rect.Min.y < scroll_rect.Min.y || !can_be_fully_visible_y)
10361
0
            SetScrollFromPosY(window, item_rect.Min.y - g.Style.ItemSpacing.y - window->Pos.y, 0.0f);
10362
0
        else if (item_rect.Max.y >= scroll_rect.Max.y)
10363
0
            SetScrollFromPosY(window, item_rect.Max.y + g.Style.ItemSpacing.y - window->Pos.y, 1.0f);
10364
0
    }
10365
5
    else if (((flags & ImGuiScrollFlags_KeepVisibleCenterY) && !fully_visible_y) || (flags & ImGuiScrollFlags_AlwaysCenterY))
10366
0
    {
10367
0
        if (can_be_fully_visible_y)
10368
0
            SetScrollFromPosY(window, ImFloor((item_rect.Min.y + item_rect.Max.y) * 0.5f) - window->Pos.y, 0.5f);
10369
0
        else
10370
0
            SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y, 0.0f);
10371
0
    }
10372
10373
5
    ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
10374
5
    ImVec2 delta_scroll = next_scroll - window->Scroll;
10375
10376
    // Also scroll parent window to keep us into view if necessary
10377
5
    if (!(flags & ImGuiScrollFlags_NoScrollParent) && (window->Flags & ImGuiWindowFlags_ChildWindow))
10378
0
    {
10379
        // FIXME-SCROLL: May be an option?
10380
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterX | ImGuiScrollFlags_KeepVisibleCenterX)) != 0)
10381
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskX_) | ImGuiScrollFlags_KeepVisibleEdgeX;
10382
0
        if ((in_flags & (ImGuiScrollFlags_AlwaysCenterY | ImGuiScrollFlags_KeepVisibleCenterY)) != 0)
10383
0
            in_flags = (in_flags & ~ImGuiScrollFlags_MaskY_) | ImGuiScrollFlags_KeepVisibleEdgeY;
10384
0
        delta_scroll += ScrollToRectEx(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll), in_flags);
10385
0
    }
10386
10387
5
    return delta_scroll;
10388
5
}
10389
10390
float ImGui::GetScrollX()
10391
4.06k
{
10392
4.06k
    ImGuiWindow* window = GImGui->CurrentWindow;
10393
4.06k
    return window->Scroll.x;
10394
4.06k
}
10395
10396
float ImGui::GetScrollY()
10397
4.06k
{
10398
4.06k
    ImGuiWindow* window = GImGui->CurrentWindow;
10399
4.06k
    return window->Scroll.y;
10400
4.06k
}
10401
10402
float ImGui::GetScrollMaxX()
10403
0
{
10404
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10405
0
    return window->ScrollMax.x;
10406
0
}
10407
10408
float ImGui::GetScrollMaxY()
10409
0
{
10410
0
    ImGuiWindow* window = GImGui->CurrentWindow;
10411
0
    return window->ScrollMax.y;
10412
0
}
10413
10414
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
10415
1.05k
{
10416
1.05k
    window->ScrollTarget.x = scroll_x;
10417
1.05k
    window->ScrollTargetCenterRatio.x = 0.0f;
10418
1.05k
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10419
1.05k
}
10420
10421
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
10422
906
{
10423
906
    window->ScrollTarget.y = scroll_y;
10424
906
    window->ScrollTargetCenterRatio.y = 0.0f;
10425
906
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10426
906
}
10427
10428
void ImGui::SetScrollX(float scroll_x)
10429
1.03k
{
10430
1.03k
    ImGuiContext& g = *GImGui;
10431
1.03k
    SetScrollX(g.CurrentWindow, scroll_x);
10432
1.03k
}
10433
10434
void ImGui::SetScrollY(float scroll_y)
10435
881
{
10436
881
    ImGuiContext& g = *GImGui;
10437
881
    SetScrollY(g.CurrentWindow, scroll_y);
10438
881
}
10439
10440
// Note that a local position will vary depending on initial scroll value,
10441
// This is a little bit confusing so bear with us:
10442
//  - local_pos = (absolution_pos - window->Pos)
10443
//  - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
10444
//    and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
10445
//  - They mostly exist because of legacy API.
10446
// Following the rules above, when trying to work with scrolling code, consider that:
10447
//  - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
10448
//  - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
10449
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
10450
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
10451
0
{
10452
0
    IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
10453
0
    window->ScrollTarget.x = IM_FLOOR(local_x - window->DecoOuterSizeX1 - window->DecoInnerSizeX1 + window->Scroll.x); // Convert local position to scroll offset
10454
0
    window->ScrollTargetCenterRatio.x = center_x_ratio;
10455
0
    window->ScrollTargetEdgeSnapDist.x = 0.0f;
10456
0
}
10457
10458
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
10459
0
{
10460
0
    IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
10461
0
    window->ScrollTarget.y = IM_FLOOR(local_y - window->DecoOuterSizeY1 - window->DecoInnerSizeY1 + window->Scroll.y); // Convert local position to scroll offset
10462
0
    window->ScrollTargetCenterRatio.y = center_y_ratio;
10463
0
    window->ScrollTargetEdgeSnapDist.y = 0.0f;
10464
0
}
10465
10466
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
10467
0
{
10468
0
    ImGuiContext& g = *GImGui;
10469
0
    SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
10470
0
}
10471
10472
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
10473
0
{
10474
0
    ImGuiContext& g = *GImGui;
10475
0
    SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
10476
0
}
10477
10478
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
10479
void ImGui::SetScrollHereX(float center_x_ratio)
10480
0
{
10481
0
    ImGuiContext& g = *GImGui;
10482
0
    ImGuiWindow* window = g.CurrentWindow;
10483
0
    float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
10484
0
    float target_pos_x = ImLerp(g.LastItemData.Rect.Min.x - spacing_x, g.LastItemData.Rect.Max.x + spacing_x, center_x_ratio);
10485
0
    SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
10486
10487
    // Tweak: snap on edges when aiming at an item very close to the edge
10488
0
    window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
10489
0
}
10490
10491
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
10492
void ImGui::SetScrollHereY(float center_y_ratio)
10493
0
{
10494
0
    ImGuiContext& g = *GImGui;
10495
0
    ImGuiWindow* window = g.CurrentWindow;
10496
0
    float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
10497
0
    float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
10498
0
    SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
10499
10500
    // Tweak: snap on edges when aiming at an item very close to the edge
10501
0
    window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
10502
0
}
10503
10504
//-----------------------------------------------------------------------------
10505
// [SECTION] TOOLTIPS
10506
//-----------------------------------------------------------------------------
10507
10508
void ImGui::BeginTooltip()
10509
0
{
10510
0
    BeginTooltipEx(ImGuiTooltipFlags_None, ImGuiWindowFlags_None);
10511
0
}
10512
10513
void ImGui::BeginTooltipEx(ImGuiTooltipFlags tooltip_flags, ImGuiWindowFlags extra_window_flags)
10514
0
{
10515
0
    ImGuiContext& g = *GImGui;
10516
10517
0
    if (g.DragDropWithinSource || g.DragDropWithinTarget)
10518
0
    {
10519
        // The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
10520
        // In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
10521
        // Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
10522
        //ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
10523
0
        ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
10524
0
        SetNextWindowPos(tooltip_pos);
10525
0
        SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
10526
        //PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
10527
0
        tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
10528
0
    }
10529
10530
0
    char window_name[16];
10531
0
    ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
10532
0
    if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
10533
0
        if (ImGuiWindow* window = FindWindowByName(window_name))
10534
0
            if (window->Active)
10535
0
            {
10536
                // Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
10537
0
                window->Hidden = true;
10538
0
                window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
10539
0
                ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
10540
0
            }
10541
0
    ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoDocking;
10542
0
    Begin(window_name, NULL, flags | extra_window_flags);
10543
0
}
10544
10545
void ImGui::EndTooltip()
10546
0
{
10547
0
    IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip);   // Mismatched BeginTooltip()/EndTooltip() calls
10548
0
    End();
10549
0
}
10550
10551
void ImGui::SetTooltipV(const char* fmt, va_list args)
10552
0
{
10553
0
    BeginTooltipEx(ImGuiTooltipFlags_OverridePreviousTooltip, ImGuiWindowFlags_None);
10554
0
    TextV(fmt, args);
10555
0
    EndTooltip();
10556
0
}
10557
10558
void ImGui::SetTooltip(const char* fmt, ...)
10559
0
{
10560
0
    va_list args;
10561
0
    va_start(args, fmt);
10562
0
    SetTooltipV(fmt, args);
10563
0
    va_end(args);
10564
0
}
10565
10566
//-----------------------------------------------------------------------------
10567
// [SECTION] POPUPS
10568
//-----------------------------------------------------------------------------
10569
10570
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
10571
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
10572
0
{
10573
0
    ImGuiContext& g = *GImGui;
10574
0
    if (popup_flags & ImGuiPopupFlags_AnyPopupId)
10575
0
    {
10576
        // Return true if any popup is open at the current BeginPopup() level of the popup stack
10577
        // This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
10578
0
        IM_ASSERT(id == 0);
10579
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10580
0
            return g.OpenPopupStack.Size > 0;
10581
0
        else
10582
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
10583
0
    }
10584
0
    else
10585
0
    {
10586
0
        if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
10587
0
        {
10588
            // Return true if the popup is open anywhere in the popup stack
10589
0
            for (int n = 0; n < g.OpenPopupStack.Size; n++)
10590
0
                if (g.OpenPopupStack[n].PopupId == id)
10591
0
                    return true;
10592
0
            return false;
10593
0
        }
10594
0
        else
10595
0
        {
10596
            // Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
10597
0
            return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
10598
0
        }
10599
0
    }
10600
0
}
10601
10602
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
10603
0
{
10604
0
    ImGuiContext& g = *GImGui;
10605
0
    ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
10606
0
    if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
10607
0
        IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
10608
0
    return IsPopupOpen(id, popup_flags);
10609
0
}
10610
10611
ImGuiWindow* ImGui::GetTopMostPopupModal()
10612
103k
{
10613
103k
    ImGuiContext& g = *GImGui;
10614
103k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10615
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10616
0
            if (popup->Flags & ImGuiWindowFlags_Modal)
10617
0
                return popup;
10618
103k
    return NULL;
10619
103k
}
10620
10621
ImGuiWindow* ImGui::GetTopMostAndVisiblePopupModal()
10622
34.4k
{
10623
34.4k
    ImGuiContext& g = *GImGui;
10624
34.4k
    for (int n = g.OpenPopupStack.Size - 1; n >= 0; n--)
10625
0
        if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
10626
0
            if ((popup->Flags & ImGuiWindowFlags_Modal) && IsWindowActiveAndVisible(popup))
10627
0
                return popup;
10628
34.4k
    return NULL;
10629
34.4k
}
10630
10631
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
10632
0
{
10633
0
    ImGuiContext& g = *GImGui;
10634
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10635
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopup(\"%s\" -> 0x%08X\n", str_id, id);
10636
0
    OpenPopupEx(id, popup_flags);
10637
0
}
10638
10639
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
10640
0
{
10641
0
    OpenPopupEx(id, popup_flags);
10642
0
}
10643
10644
// Mark popup as open (toggle toward open state).
10645
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
10646
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
10647
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
10648
void ImGui::OpenPopupEx(ImGuiID id, ImGuiPopupFlags popup_flags)
10649
0
{
10650
0
    ImGuiContext& g = *GImGui;
10651
0
    ImGuiWindow* parent_window = g.CurrentWindow;
10652
0
    const int current_stack_size = g.BeginPopupStack.Size;
10653
10654
0
    if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
10655
0
        if (IsPopupOpen((ImGuiID)0, ImGuiPopupFlags_AnyPopupId))
10656
0
            return;
10657
10658
0
    ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
10659
0
    popup_ref.PopupId = id;
10660
0
    popup_ref.Window = NULL;
10661
0
    popup_ref.BackupNavWindow = g.NavWindow;            // When popup closes focus may be restored to NavWindow (depend on window type).
10662
0
    popup_ref.OpenFrameCount = g.FrameCount;
10663
0
    popup_ref.OpenParentId = parent_window->IDStack.back();
10664
0
    popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
10665
0
    popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
10666
10667
0
    IMGUI_DEBUG_LOG_POPUP("[popup] OpenPopupEx(0x%08X)\n", id);
10668
0
    if (g.OpenPopupStack.Size < current_stack_size + 1)
10669
0
    {
10670
0
        g.OpenPopupStack.push_back(popup_ref);
10671
0
    }
10672
0
    else
10673
0
    {
10674
        // Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
10675
        // would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
10676
        // situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
10677
0
        if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
10678
0
        {
10679
0
            g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
10680
0
        }
10681
0
        else
10682
0
        {
10683
            // Close child popups if any, then flag popup for open/reopen
10684
0
            ClosePopupToLevel(current_stack_size, false);
10685
0
            g.OpenPopupStack.push_back(popup_ref);
10686
0
        }
10687
10688
        // When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
10689
        // This is equivalent to what ClosePopupToLevel() does.
10690
        //if (g.OpenPopupStack[current_stack_size].PopupId == id)
10691
        //    FocusWindow(parent_window);
10692
0
    }
10693
0
}
10694
10695
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
10696
// This function closes any popups that are over 'ref_window'.
10697
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
10698
2.09k
{
10699
2.09k
    ImGuiContext& g = *GImGui;
10700
2.09k
    if (g.OpenPopupStack.Size == 0)
10701
2.09k
        return;
10702
10703
    // Don't close our own child popup windows.
10704
0
    int popup_count_to_keep = 0;
10705
0
    if (ref_window)
10706
0
    {
10707
        // Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
10708
0
        for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
10709
0
        {
10710
0
            ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
10711
0
            if (!popup.Window)
10712
0
                continue;
10713
0
            IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
10714
0
            if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
10715
0
                continue;
10716
10717
            // Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
10718
            // - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
10719
            //     Window -> Popup1 -> Popup2 -> Popup3
10720
            // - Each popups may contain child windows, which is why we compare ->RootWindowDockTree!
10721
            //     Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
10722
0
            bool ref_window_is_descendent_of_popup = false;
10723
0
            for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
10724
0
                if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
10725
                    //if (popup_window->RootWindowDockTree == ref_window->RootWindowDockTree) // FIXME-MERGE
10726
0
                    if (IsWindowWithinBeginStackOf(ref_window, popup_window))
10727
0
                    {
10728
0
                        ref_window_is_descendent_of_popup = true;
10729
0
                        break;
10730
0
                    }
10731
0
            if (!ref_window_is_descendent_of_popup)
10732
0
                break;
10733
0
        }
10734
0
    }
10735
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10736
0
    {
10737
0
        IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupsOverWindow(\"%s\")\n", ref_window ? ref_window->Name : "<NULL>");
10738
0
        ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
10739
0
    }
10740
0
}
10741
10742
void ImGui::ClosePopupsExceptModals()
10743
0
{
10744
0
    ImGuiContext& g = *GImGui;
10745
10746
0
    int popup_count_to_keep;
10747
0
    for (popup_count_to_keep = g.OpenPopupStack.Size; popup_count_to_keep > 0; popup_count_to_keep--)
10748
0
    {
10749
0
        ImGuiWindow* window = g.OpenPopupStack[popup_count_to_keep - 1].Window;
10750
0
        if (!window || window->Flags & ImGuiWindowFlags_Modal)
10751
0
            break;
10752
0
    }
10753
0
    if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
10754
0
        ClosePopupToLevel(popup_count_to_keep, true);
10755
0
}
10756
10757
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
10758
0
{
10759
0
    ImGuiContext& g = *GImGui;
10760
0
    IMGUI_DEBUG_LOG_POPUP("[popup] ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
10761
0
    IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
10762
10763
    // Trim open popup stack
10764
0
    ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
10765
0
    ImGuiWindow* popup_backup_nav_window = g.OpenPopupStack[remaining].BackupNavWindow;
10766
0
    g.OpenPopupStack.resize(remaining);
10767
10768
0
    if (restore_focus_to_window_under_popup)
10769
0
    {
10770
0
        ImGuiWindow* focus_window = (popup_window && popup_window->Flags & ImGuiWindowFlags_ChildMenu) ? popup_window->ParentWindow : popup_backup_nav_window;
10771
0
        if (focus_window && !focus_window->WasActive && popup_window)
10772
0
        {
10773
            // Fallback
10774
0
            FocusTopMostWindowUnderOne(popup_window, NULL);
10775
0
        }
10776
0
        else
10777
0
        {
10778
0
            if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
10779
0
                focus_window = NavRestoreLastChildNavWindow(focus_window);
10780
0
            FocusWindow(focus_window);
10781
0
        }
10782
0
    }
10783
0
}
10784
10785
// Close the popup we have begin-ed into.
10786
void ImGui::CloseCurrentPopup()
10787
0
{
10788
0
    ImGuiContext& g = *GImGui;
10789
0
    int popup_idx = g.BeginPopupStack.Size - 1;
10790
0
    if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
10791
0
        return;
10792
10793
    // Closing a menu closes its top-most parent popup (unless a modal)
10794
0
    while (popup_idx > 0)
10795
0
    {
10796
0
        ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
10797
0
        ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
10798
0
        bool close_parent = false;
10799
0
        if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
10800
0
            if (parent_popup_window && !(parent_popup_window->Flags & ImGuiWindowFlags_MenuBar))
10801
0
                close_parent = true;
10802
0
        if (!close_parent)
10803
0
            break;
10804
0
        popup_idx--;
10805
0
    }
10806
0
    IMGUI_DEBUG_LOG_POPUP("[popup] CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
10807
0
    ClosePopupToLevel(popup_idx, true);
10808
10809
    // A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
10810
    // To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
10811
    // Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
10812
0
    if (ImGuiWindow* window = g.NavWindow)
10813
0
        window->DC.NavHideHighlightOneFrame = true;
10814
0
}
10815
10816
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
10817
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
10818
0
{
10819
0
    ImGuiContext& g = *GImGui;
10820
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10821
0
    {
10822
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10823
0
        return false;
10824
0
    }
10825
10826
0
    char name[20];
10827
0
    if (flags & ImGuiWindowFlags_ChildMenu)
10828
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginMenuCount); // Recycle windows based on depth
10829
0
    else
10830
0
        ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
10831
10832
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoDocking;
10833
0
    bool is_open = Begin(name, NULL, flags);
10834
0
    if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
10835
0
        EndPopup();
10836
10837
0
    return is_open;
10838
0
}
10839
10840
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
10841
0
{
10842
0
    ImGuiContext& g = *GImGui;
10843
0
    if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
10844
0
    {
10845
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10846
0
        return false;
10847
0
    }
10848
0
    flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
10849
0
    ImGuiID id = g.CurrentWindow->GetID(str_id);
10850
0
    return BeginPopupEx(id, flags);
10851
0
}
10852
10853
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
10854
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
10855
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
10856
0
{
10857
0
    ImGuiContext& g = *GImGui;
10858
0
    ImGuiWindow* window = g.CurrentWindow;
10859
0
    const ImGuiID id = window->GetID(name);
10860
0
    if (!IsPopupOpen(id, ImGuiPopupFlags_None))
10861
0
    {
10862
0
        g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
10863
0
        return false;
10864
0
    }
10865
10866
    // Center modal windows by default for increased visibility
10867
    // (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
10868
    // FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
10869
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
10870
0
    {
10871
0
        const ImGuiViewport* viewport = window->WasActive ? window->Viewport : GetMainViewport(); // FIXME-VIEWPORT: What may be our reference viewport?
10872
0
        SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
10873
0
    }
10874
10875
0
    flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoDocking;
10876
0
    const bool is_open = Begin(name, p_open, flags);
10877
0
    if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
10878
0
    {
10879
0
        EndPopup();
10880
0
        if (is_open)
10881
0
            ClosePopupToLevel(g.BeginPopupStack.Size, true);
10882
0
        return false;
10883
0
    }
10884
0
    return is_open;
10885
0
}
10886
10887
void ImGui::EndPopup()
10888
0
{
10889
0
    ImGuiContext& g = *GImGui;
10890
0
    ImGuiWindow* window = g.CurrentWindow;
10891
0
    IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup);  // Mismatched BeginPopup()/EndPopup() calls
10892
0
    IM_ASSERT(g.BeginPopupStack.Size > 0);
10893
10894
    // Make all menus and popups wrap around for now, may need to expose that policy (e.g. focus scope could include wrap/loop policy flags used by new move requests)
10895
0
    if (g.NavWindow == window)
10896
0
        NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
10897
10898
    // Child-popups don't need to be laid out
10899
0
    IM_ASSERT(g.WithinEndChild == false);
10900
0
    if (window->Flags & ImGuiWindowFlags_ChildWindow)
10901
0
        g.WithinEndChild = true;
10902
0
    End();
10903
0
    g.WithinEndChild = false;
10904
0
}
10905
10906
// Helper to open a popup if mouse button is released over the item
10907
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
10908
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
10909
0
{
10910
0
    ImGuiContext& g = *GImGui;
10911
0
    ImGuiWindow* window = g.CurrentWindow;
10912
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10913
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10914
0
    {
10915
0
        ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10916
0
        IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10917
0
        OpenPopupEx(id, popup_flags);
10918
0
    }
10919
0
}
10920
10921
// This is a helper to handle the simplest case of associating one named popup to one given widget.
10922
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
10923
// - To create a popup with a specific identifier, pass it in str_id.
10924
//    - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
10925
//    - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
10926
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
10927
//   This is essentially the same as:
10928
//       id = str_id ? GetID(str_id) : GetItemID();
10929
//       OpenPopupOnItemClick(str_id, ImGuiPopupFlags_MouseButtonRight);
10930
//       return BeginPopup(id);
10931
//   Which is essentially the same as:
10932
//       id = str_id ? GetID(str_id) : GetItemID();
10933
//       if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
10934
//           OpenPopup(id);
10935
//       return BeginPopup(id);
10936
//   The main difference being that this is tweaked to avoid computing the ID twice.
10937
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
10938
0
{
10939
0
    ImGuiContext& g = *GImGui;
10940
0
    ImGuiWindow* window = g.CurrentWindow;
10941
0
    if (window->SkipItems)
10942
0
        return false;
10943
0
    ImGuiID id = str_id ? window->GetID(str_id) : g.LastItemData.ID;    // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
10944
0
    IM_ASSERT(id != 0);                                             // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
10945
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10946
0
    if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10947
0
        OpenPopupEx(id, popup_flags);
10948
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10949
0
}
10950
10951
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
10952
0
{
10953
0
    ImGuiContext& g = *GImGui;
10954
0
    ImGuiWindow* window = g.CurrentWindow;
10955
0
    if (!str_id)
10956
0
        str_id = "window_context";
10957
0
    ImGuiID id = window->GetID(str_id);
10958
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10959
0
    if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
10960
0
        if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
10961
0
            OpenPopupEx(id, popup_flags);
10962
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10963
0
}
10964
10965
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
10966
0
{
10967
0
    ImGuiContext& g = *GImGui;
10968
0
    ImGuiWindow* window = g.CurrentWindow;
10969
0
    if (!str_id)
10970
0
        str_id = "void_context";
10971
0
    ImGuiID id = window->GetID(str_id);
10972
0
    int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
10973
0
    if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
10974
0
        if (GetTopMostPopupModal() == NULL)
10975
0
            OpenPopupEx(id, popup_flags);
10976
0
    return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
10977
0
}
10978
10979
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
10980
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
10981
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
10982
//  information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
10983
//  this allows us to have tooltips/popups displayed out of the parent viewport.)
10984
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
10985
0
{
10986
0
    ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
10987
    //GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
10988
    //GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
10989
10990
    // Combo Box policy (we want a connecting edge)
10991
0
    if (policy == ImGuiPopupPositionPolicy_ComboBox)
10992
0
    {
10993
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
10994
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
10995
0
        {
10996
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
10997
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
10998
0
                continue;
10999
0
            ImVec2 pos;
11000
0
            if (dir == ImGuiDir_Down)  pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y);          // Below, Toward Right (default)
11001
0
            if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
11002
0
            if (dir == ImGuiDir_Left)  pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
11003
0
            if (dir == ImGuiDir_Up)    pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
11004
0
            if (!r_outer.Contains(ImRect(pos, pos + size)))
11005
0
                continue;
11006
0
            *last_dir = dir;
11007
0
            return pos;
11008
0
        }
11009
0
    }
11010
11011
    // Tooltip and Default popup policy
11012
    // (Always first try the direction we used on the last frame, if any)
11013
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
11014
0
    {
11015
0
        const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
11016
0
        for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
11017
0
        {
11018
0
            const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
11019
0
            if (n != -1 && dir == *last_dir) // Already tried this direction?
11020
0
                continue;
11021
11022
0
            const float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
11023
0
            const float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
11024
11025
            // If there's not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
11026
0
            if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
11027
0
                continue;
11028
0
            if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
11029
0
                continue;
11030
11031
0
            ImVec2 pos;
11032
0
            pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
11033
0
            pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
11034
11035
            // Clamp top-left corner of popup
11036
0
            pos.x = ImMax(pos.x, r_outer.Min.x);
11037
0
            pos.y = ImMax(pos.y, r_outer.Min.y);
11038
11039
0
            *last_dir = dir;
11040
0
            return pos;
11041
0
        }
11042
0
    }
11043
11044
    // Fallback when not enough room:
11045
0
    *last_dir = ImGuiDir_None;
11046
11047
    // For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
11048
0
    if (policy == ImGuiPopupPositionPolicy_Tooltip)
11049
0
        return ref_pos + ImVec2(2, 2);
11050
11051
    // Otherwise try to keep within display
11052
0
    ImVec2 pos = ref_pos;
11053
0
    pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
11054
0
    pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
11055
0
    return pos;
11056
0
}
11057
11058
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
11059
ImRect ImGui::GetPopupAllowedExtentRect(ImGuiWindow* window)
11060
0
{
11061
0
    ImGuiContext& g = *GImGui;
11062
0
    ImRect r_screen;
11063
0
    if (window->ViewportAllowPlatformMonitorExtend >= 0)
11064
0
    {
11065
        // Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
11066
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
11067
0
        r_screen.Min = monitor.WorkPos;
11068
0
        r_screen.Max = monitor.WorkPos + monitor.WorkSize;
11069
0
    }
11070
0
    else
11071
0
    {
11072
        // Use the full viewport area (not work area) for popups
11073
0
        r_screen = window->Viewport->GetMainRect();
11074
0
    }
11075
0
    ImVec2 padding = g.Style.DisplaySafeAreaPadding;
11076
0
    r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
11077
0
    return r_screen;
11078
0
}
11079
11080
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
11081
0
{
11082
0
    ImGuiContext& g = *GImGui;
11083
11084
0
    ImRect r_outer = GetPopupAllowedExtentRect(window);
11085
0
    if (window->Flags & ImGuiWindowFlags_ChildMenu)
11086
0
    {
11087
        // Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
11088
        // This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
11089
0
        ImGuiWindow* parent_window = window->ParentWindow;
11090
0
        float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
11091
0
        ImRect r_avoid;
11092
0
        if (parent_window->DC.MenuBarAppending)
11093
0
            r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
11094
0
        else
11095
0
            r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
11096
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
11097
0
    }
11098
0
    if (window->Flags & ImGuiWindowFlags_Popup)
11099
0
    {
11100
0
        return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, ImRect(window->Pos, window->Pos), ImGuiPopupPositionPolicy_Default); // Ideally we'd disable r_avoid here
11101
0
    }
11102
0
    if (window->Flags & ImGuiWindowFlags_Tooltip)
11103
0
    {
11104
        // Position tooltip (always follows mouse)
11105
0
        float sc = g.Style.MouseCursorScale;
11106
0
        ImVec2 ref_pos = NavCalcPreferredRefPos();
11107
0
        ImRect r_avoid;
11108
0
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
11109
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
11110
0
        else
11111
0
            r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
11112
0
        return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
11113
0
    }
11114
0
    IM_ASSERT(0);
11115
0
    return window->Pos;
11116
0
}
11117
11118
//-----------------------------------------------------------------------------
11119
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
11120
//-----------------------------------------------------------------------------
11121
11122
// FIXME-NAV: The existence of SetNavID vs SetFocusID vs FocusWindow() needs to be clarified/reworked.
11123
// In our terminology those should be interchangeable, yet right now this is super confusing.
11124
// Those two functions are merely a legacy artifact, so at minimum naming should be clarified.
11125
11126
void ImGui::SetNavWindow(ImGuiWindow* window)
11127
1.88k
{
11128
1.88k
    ImGuiContext& g = *GImGui;
11129
1.88k
    if (g.NavWindow != window)
11130
1.88k
    {
11131
1.88k
        IMGUI_DEBUG_LOG_FOCUS("[focus] SetNavWindow(\"%s\")\n", window ? window->Name : "<NULL>");
11132
1.88k
        g.NavWindow = window;
11133
1.88k
    }
11134
1.88k
    g.NavInitRequest = g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11135
1.88k
    NavUpdateAnyRequestFlag();
11136
1.88k
}
11137
11138
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
11139
46
{
11140
46
    ImGuiContext& g = *GImGui;
11141
46
    IM_ASSERT(g.NavWindow != NULL);
11142
46
    IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
11143
46
    g.NavId = id;
11144
46
    g.NavLayer = nav_layer;
11145
46
    g.NavFocusScopeId = focus_scope_id;
11146
46
    g.NavWindow->NavLastIds[nav_layer] = id;
11147
46
    g.NavWindow->NavRectRel[nav_layer] = rect_rel;
11148
46
}
11149
11150
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
11151
80
{
11152
80
    ImGuiContext& g = *GImGui;
11153
80
    IM_ASSERT(id != 0);
11154
11155
80
    if (g.NavWindow != window)
11156
62
       SetNavWindow(window);
11157
11158
    // Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and g.CurrentFocusScopeId are valid.
11159
    // Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
11160
80
    const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
11161
80
    g.NavId = id;
11162
80
    g.NavLayer = nav_layer;
11163
80
    g.NavFocusScopeId = g.CurrentFocusScopeId;
11164
80
    window->NavLastIds[nav_layer] = id;
11165
80
    if (g.LastItemData.ID == id)
11166
80
        window->NavRectRel[nav_layer] = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11167
11168
80
    if (g.ActiveIdSource == ImGuiInputSource_Nav)
11169
0
        g.NavDisableMouseHover = true;
11170
80
    else
11171
80
        g.NavDisableHighlight = true;
11172
80
}
11173
11174
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
11175
7
{
11176
7
    if (ImFabs(dx) > ImFabs(dy))
11177
0
        return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
11178
7
    return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
11179
7
}
11180
11181
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
11182
14
{
11183
14
    if (a1 < b0)
11184
7
        return a1 - b0;
11185
7
    if (b1 < a0)
11186
7
        return a0 - b1;
11187
0
    return 0.0f;
11188
7
}
11189
11190
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
11191
7
{
11192
7
    if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11193
0
    {
11194
0
        r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
11195
0
        r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
11196
0
    }
11197
7
    else // FIXME: PageUp/PageDown are leaving move_dir == None
11198
7
    {
11199
7
        r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
11200
7
        r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
11201
7
    }
11202
7
}
11203
11204
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
11205
static bool ImGui::NavScoreItem(ImGuiNavItemData* result)
11206
24
{
11207
24
    ImGuiContext& g = *GImGui;
11208
24
    ImGuiWindow* window = g.CurrentWindow;
11209
24
    if (g.NavLayer != window->DC.NavLayerCurrent)
11210
17
        return false;
11211
11212
    // FIXME: Those are not good variables names
11213
7
    ImRect cand = g.LastItemData.NavRect;   // Current item nav rectangle
11214
7
    const ImRect curr = g.NavScoringRect;   // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
11215
7
    g.NavScoringDebugCount++;
11216
11217
    // When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
11218
7
    if (window->ParentWindow == g.NavWindow)
11219
0
    {
11220
0
        IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
11221
0
        if (!window->ClipRect.Overlaps(cand))
11222
0
            return false;
11223
0
        cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
11224
0
    }
11225
11226
    // We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
11227
    // For example, this ensures that items in one column are not reached when moving vertically from items in another column.
11228
7
    NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
11229
11230
    // Compute distance between boxes
11231
    // FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
11232
7
    float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
11233
7
    float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
11234
7
    if (dby != 0.0f && dbx != 0.0f)
11235
7
        dbx = (dbx / 1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
11236
7
    float dist_box = ImFabs(dbx) + ImFabs(dby);
11237
11238
    // Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
11239
7
    float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
11240
7
    float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
11241
7
    float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
11242
11243
    // Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
11244
7
    ImGuiDir quadrant;
11245
7
    float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
11246
7
    if (dbx != 0.0f || dby != 0.0f)
11247
7
    {
11248
        // For non-overlapping boxes, use distance between boxes
11249
7
        dax = dbx;
11250
7
        day = dby;
11251
7
        dist_axial = dist_box;
11252
7
        quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
11253
7
    }
11254
0
    else if (dcx != 0.0f || dcy != 0.0f)
11255
0
    {
11256
        // For overlapping boxes with different centers, use distance between centers
11257
0
        dax = dcx;
11258
0
        day = dcy;
11259
0
        dist_axial = dist_center;
11260
0
        quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
11261
0
    }
11262
0
    else
11263
0
    {
11264
        // Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
11265
0
        quadrant = (g.LastItemData.ID < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
11266
0
    }
11267
11268
#if IMGUI_DEBUG_NAV_SCORING
11269
    char buf[128];
11270
    if (IsMouseHoveringRect(cand.Min, cand.Max))
11271
    {
11272
        ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
11273
        ImDrawList* draw_list = GetForegroundDrawList(window);
11274
        draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
11275
        draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
11276
        draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
11277
        draw_list->AddText(cand.Max, ~0U, buf);
11278
    }
11279
    else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
11280
    {
11281
        if (quadrant == g.NavMoveDir)
11282
        {
11283
            ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
11284
            ImDrawList* draw_list = GetForegroundDrawList(window);
11285
            draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
11286
            draw_list->AddText(cand.Min, IM_COL32(255, 255, 255, 255), buf);
11287
        }
11288
    }
11289
#endif
11290
11291
    // Is it in the quadrant we're interested in moving to?
11292
7
    bool new_best = false;
11293
7
    const ImGuiDir move_dir = g.NavMoveDir;
11294
7
    if (quadrant == move_dir)
11295
7
    {
11296
        // Does it beat the current best candidate?
11297
7
        if (dist_box < result->DistBox)
11298
7
        {
11299
7
            result->DistBox = dist_box;
11300
7
            result->DistCenter = dist_center;
11301
7
            return true;
11302
7
        }
11303
0
        if (dist_box == result->DistBox)
11304
0
        {
11305
            // Try using distance between center points to break ties
11306
0
            if (dist_center < result->DistCenter)
11307
0
            {
11308
0
                result->DistCenter = dist_center;
11309
0
                new_best = true;
11310
0
            }
11311
0
            else if (dist_center == result->DistCenter)
11312
0
            {
11313
                // Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
11314
                // (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
11315
                // this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
11316
0
                if (((move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
11317
0
                    new_best = true;
11318
0
            }
11319
0
        }
11320
0
    }
11321
11322
    // Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
11323
    // are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
11324
    // This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
11325
    // 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
11326
    // Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
11327
0
    if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial)  // Check axial match
11328
0
        if (g.NavLayer == ImGuiNavLayer_Menu && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
11329
0
            if ((move_dir == ImGuiDir_Left && dax < 0.0f) || (move_dir == ImGuiDir_Right && dax > 0.0f) || (move_dir == ImGuiDir_Up && day < 0.0f) || (move_dir == ImGuiDir_Down && day > 0.0f))
11330
0
            {
11331
0
                result->DistAxial = dist_axial;
11332
0
                new_best = true;
11333
0
            }
11334
11335
0
    return new_best;
11336
7
}
11337
11338
static void ImGui::NavApplyItemToResult(ImGuiNavItemData* result)
11339
7
{
11340
7
    ImGuiContext& g = *GImGui;
11341
7
    ImGuiWindow* window = g.CurrentWindow;
11342
7
    result->Window = window;
11343
7
    result->ID = g.LastItemData.ID;
11344
7
    result->FocusScopeId = g.CurrentFocusScopeId;
11345
7
    result->InFlags = g.LastItemData.InFlags;
11346
7
    result->RectRel = WindowRectAbsToRel(window, g.LastItemData.NavRect);
11347
7
}
11348
11349
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
11350
// This is called after LastItemData is set.
11351
static void ImGui::NavProcessItem()
11352
326
{
11353
326
    ImGuiContext& g = *GImGui;
11354
326
    ImGuiWindow* window = g.CurrentWindow;
11355
326
    const ImGuiID id = g.LastItemData.ID;
11356
326
    const ImRect nav_bb = g.LastItemData.NavRect;
11357
326
    const ImGuiItemFlags item_flags = g.LastItemData.InFlags;
11358
11359
    // Process Init Request
11360
326
    if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent && (item_flags & ImGuiItemFlags_Disabled) == 0)
11361
0
    {
11362
        // Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
11363
0
        const bool candidate_for_nav_default_focus = (item_flags & ImGuiItemFlags_NoNavDefaultFocus) == 0;
11364
0
        if (candidate_for_nav_default_focus || g.NavInitResultId == 0)
11365
0
        {
11366
0
            g.NavInitResultId = id;
11367
0
            g.NavInitResultRectRel = WindowRectAbsToRel(window, nav_bb);
11368
0
        }
11369
0
        if (candidate_for_nav_default_focus)
11370
0
        {
11371
0
            g.NavInitRequest = false; // Found a match, clear request
11372
0
            NavUpdateAnyRequestFlag();
11373
0
        }
11374
0
    }
11375
11376
    // Process Move Request (scoring for navigation)
11377
    // FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRect + scoring from a rect wrapped according to current wrapping policy)
11378
326
    if (g.NavMoveScoringItems)
11379
21
    {
11380
21
        const bool is_tab_stop = (item_flags & ImGuiItemFlags_Inputable) && (item_flags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
11381
21
        const bool is_tabbing = (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) != 0;
11382
21
        if (is_tabbing)
11383
0
        {
11384
0
            if (is_tab_stop || (g.NavMoveFlags & ImGuiNavMoveFlags_FocusApi))
11385
0
                NavProcessItemForTabbingRequest(id);
11386
0
        }
11387
21
        else if ((g.NavId != id || (g.NavMoveFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_Disabled))
11388
17
        {
11389
17
            ImGuiNavItemData* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
11390
17
            if (!is_tabbing)
11391
17
            {
11392
17
                if (NavScoreItem(result))
11393
7
                    NavApplyItemToResult(result);
11394
11395
                // Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
11396
17
                const float VISIBLE_RATIO = 0.70f;
11397
17
                if ((g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
11398
7
                    if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
11399
7
                        if (NavScoreItem(&g.NavMoveResultLocalVisible))
11400
0
                            NavApplyItemToResult(&g.NavMoveResultLocalVisible);
11401
17
            }
11402
17
        }
11403
21
    }
11404
11405
    // Update window-relative bounding box of navigated item
11406
326
    if (g.NavId == id)
11407
314
    {
11408
314
        if (g.NavWindow != window)
11409
0
            SetNavWindow(window); // Always refresh g.NavWindow, because some operations such as FocusItem() may not have a window.
11410
314
        g.NavLayer = window->DC.NavLayerCurrent;
11411
314
        g.NavFocusScopeId = g.CurrentFocusScopeId;
11412
314
        g.NavIdIsAlive = true;
11413
314
        window->NavRectRel[window->DC.NavLayerCurrent] = WindowRectAbsToRel(window, nav_bb);    // Store item bounding box (relative to window position)
11414
314
    }
11415
326
}
11416
11417
// Handle "scoring" of an item for a tabbing/focusing request initiated by NavUpdateCreateTabbingRequest().
11418
// Note that SetKeyboardFocusHere() API calls are considered tabbing requests!
11419
// - Case 1: no nav/active id:    set result to first eligible item, stop storing.
11420
// - Case 2: tab forward:         on ref id set counter, on counter elapse store result
11421
// - Case 3: tab forward wrap:    set result to first eligible item (preemptively), on ref id set counter, on next frame if counter hasn't elapsed store result. // FIXME-TABBING: Could be done as a next-frame forwarded request
11422
// - Case 4: tab backward:        store all results, on ref id pick prev, stop storing
11423
// - Case 5: tab backward wrap:   store all results, on ref id if no result keep storing until last // FIXME-TABBING: Could be done as next-frame forwarded requested
11424
void ImGui::NavProcessItemForTabbingRequest(ImGuiID id)
11425
0
{
11426
0
    ImGuiContext& g = *GImGui;
11427
11428
    // Always store in NavMoveResultLocal (unlike directional request which uses NavMoveResultOther on sibling/flattened windows)
11429
0
    ImGuiNavItemData* result = &g.NavMoveResultLocal;
11430
0
    if (g.NavTabbingDir == +1)
11431
0
    {
11432
        // Tab Forward or SetKeyboardFocusHere() with >= 0
11433
0
        if (g.NavTabbingResultFirst.ID == 0)
11434
0
            NavApplyItemToResult(&g.NavTabbingResultFirst);
11435
0
        if (--g.NavTabbingCounter == 0)
11436
0
            NavMoveRequestResolveWithLastItem(result);
11437
0
        else if (g.NavId == id)
11438
0
            g.NavTabbingCounter = 1;
11439
0
    }
11440
0
    else if (g.NavTabbingDir == -1)
11441
0
    {
11442
        // Tab Backward
11443
0
        if (g.NavId == id)
11444
0
        {
11445
0
            if (result->ID)
11446
0
            {
11447
0
                g.NavMoveScoringItems = false;
11448
0
                NavUpdateAnyRequestFlag();
11449
0
            }
11450
0
        }
11451
0
        else
11452
0
        {
11453
0
            NavApplyItemToResult(result);
11454
0
        }
11455
0
    }
11456
0
    else if (g.NavTabbingDir == 0)
11457
0
    {
11458
        // Tab Init
11459
0
        if (g.NavTabbingResultFirst.ID == 0)
11460
0
            NavMoveRequestResolveWithLastItem(&g.NavTabbingResultFirst);
11461
0
    }
11462
0
}
11463
11464
bool ImGui::NavMoveRequestButNoResultYet()
11465
2.18k
{
11466
2.18k
    ImGuiContext& g = *GImGui;
11467
2.18k
    return g.NavMoveScoringItems && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
11468
2.18k
}
11469
11470
// FIXME: ScoringRect is not set
11471
void ImGui::NavMoveRequestSubmit(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11472
26
{
11473
26
    ImGuiContext& g = *GImGui;
11474
26
    IM_ASSERT(g.NavWindow != NULL);
11475
11476
26
    if (move_flags & ImGuiNavMoveFlags_Tabbing)
11477
0
        move_flags |= ImGuiNavMoveFlags_AllowCurrentNavId;
11478
11479
26
    g.NavMoveSubmitted = g.NavMoveScoringItems = true;
11480
26
    g.NavMoveDir = move_dir;
11481
26
    g.NavMoveDirForDebug = move_dir;
11482
26
    g.NavMoveClipDir = clip_dir;
11483
26
    g.NavMoveFlags = move_flags;
11484
26
    g.NavMoveScrollFlags = scroll_flags;
11485
26
    g.NavMoveForwardToNextFrame = false;
11486
26
    g.NavMoveKeyMods = g.IO.KeyMods;
11487
26
    g.NavMoveResultLocal.Clear();
11488
26
    g.NavMoveResultLocalVisible.Clear();
11489
26
    g.NavMoveResultOther.Clear();
11490
26
    g.NavTabbingCounter = 0;
11491
26
    g.NavTabbingResultFirst.Clear();
11492
26
    NavUpdateAnyRequestFlag();
11493
26
}
11494
11495
void ImGui::NavMoveRequestResolveWithLastItem(ImGuiNavItemData* result)
11496
0
{
11497
0
    ImGuiContext& g = *GImGui;
11498
0
    g.NavMoveScoringItems = false; // Ensure request doesn't need more processing
11499
0
    NavApplyItemToResult(result);
11500
0
    NavUpdateAnyRequestFlag();
11501
0
}
11502
11503
void ImGui::NavMoveRequestCancel()
11504
133
{
11505
133
    ImGuiContext& g = *GImGui;
11506
133
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11507
133
    NavUpdateAnyRequestFlag();
11508
133
}
11509
11510
// Forward will reuse the move request again on the next frame (generally with modifications done to it)
11511
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, ImGuiNavMoveFlags move_flags, ImGuiScrollFlags scroll_flags)
11512
0
{
11513
0
    ImGuiContext& g = *GImGui;
11514
0
    IM_ASSERT(g.NavMoveForwardToNextFrame == false);
11515
0
    NavMoveRequestCancel();
11516
0
    g.NavMoveForwardToNextFrame = true;
11517
0
    g.NavMoveDir = move_dir;
11518
0
    g.NavMoveClipDir = clip_dir;
11519
0
    g.NavMoveFlags = move_flags | ImGuiNavMoveFlags_Forwarded;
11520
0
    g.NavMoveScrollFlags = scroll_flags;
11521
0
}
11522
11523
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
11524
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
11525
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags wrap_flags)
11526
0
{
11527
0
    ImGuiContext& g = *GImGui;
11528
0
    IM_ASSERT(wrap_flags != 0); // Call with _WrapX, _WrapY, _LoopX, _LoopY
11529
    // In theory we should test for NavMoveRequestButNoResultYet() but there's no point doing it, NavEndFrame() will do the same test
11530
0
    if (g.NavWindow == window && g.NavMoveScoringItems && g.NavLayer == ImGuiNavLayer_Main)
11531
0
        g.NavMoveFlags |= wrap_flags;
11532
0
}
11533
11534
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
11535
// This way we could find the last focused window among our children. It would be much less confusing this way?
11536
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
11537
1.31k
{
11538
1.31k
    ImGuiWindow* parent = nav_window;
11539
2.25k
    while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
11540
937
        parent = parent->ParentWindow;
11541
1.31k
    if (parent && parent != nav_window)
11542
937
        parent->NavLastChildNavWindow = nav_window;
11543
1.31k
}
11544
11545
// Restore the last focused child.
11546
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
11547
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
11548
0
{
11549
0
    if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
11550
0
        return window->NavLastChildNavWindow;
11551
0
    if (window->DockNodeAsHost && window->DockNodeAsHost->TabBar)
11552
0
        if (ImGuiTabItem* tab = TabBarFindMostRecentlySelectedTabForActiveWindow(window->DockNodeAsHost->TabBar))
11553
0
            return tab->Window;
11554
0
    return window;
11555
0
}
11556
11557
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
11558
0
{
11559
0
    ImGuiContext& g = *GImGui;
11560
0
    if (layer == ImGuiNavLayer_Main)
11561
0
    {
11562
0
        ImGuiWindow* prev_nav_window = g.NavWindow;
11563
0
        g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);    // FIXME-NAV: Should clear ongoing nav requests?
11564
0
        if (prev_nav_window)
11565
0
            IMGUI_DEBUG_LOG_FOCUS("[focus] NavRestoreLayer: from \"%s\" to SetNavWindow(\"%s\")\n", prev_nav_window->Name, g.NavWindow->Name);
11566
0
    }
11567
0
    ImGuiWindow* window = g.NavWindow;
11568
0
    if (window->NavLastIds[layer] != 0)
11569
0
    {
11570
0
        SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
11571
0
    }
11572
0
    else
11573
0
    {
11574
0
        g.NavLayer = layer;
11575
0
        NavInitWindow(window, true);
11576
0
    }
11577
0
}
11578
11579
void ImGui::NavRestoreHighlightAfterMove()
11580
46
{
11581
46
    ImGuiContext& g = *GImGui;
11582
46
    g.NavDisableHighlight = false;
11583
46
    g.NavDisableMouseHover = g.NavMousePosDirty = true;
11584
46
}
11585
11586
static inline void ImGui::NavUpdateAnyRequestFlag()
11587
36.4k
{
11588
36.4k
    ImGuiContext& g = *GImGui;
11589
36.4k
    g.NavAnyRequest = g.NavMoveScoringItems || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
11590
36.4k
    if (g.NavAnyRequest)
11591
36.4k
        IM_ASSERT(g.NavWindow != NULL);
11592
36.4k
}
11593
11594
// This needs to be called before we submit any widget (aka in or before Begin)
11595
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
11596
2
{
11597
    // FIXME: ChildWindow test here is wrong for docking
11598
2
    ImGuiContext& g = *GImGui;
11599
2
    IM_ASSERT(window == g.NavWindow);
11600
11601
2
    if (window->Flags & ImGuiWindowFlags_NoNavInputs)
11602
0
    {
11603
0
        g.NavId = 0;
11604
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11605
0
        return;
11606
0
    }
11607
11608
2
    bool init_for_nav = false;
11609
2
    if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
11610
2
        init_for_nav = true;
11611
2
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
11612
2
    if (init_for_nav)
11613
2
    {
11614
2
        SetNavID(0, g.NavLayer, window->NavRootFocusScopeId, ImRect());
11615
2
        g.NavInitRequest = true;
11616
2
        g.NavInitRequestFromMove = false;
11617
2
        g.NavInitResultId = 0;
11618
2
        g.NavInitResultRectRel = ImRect();
11619
2
        NavUpdateAnyRequestFlag();
11620
2
    }
11621
0
    else
11622
0
    {
11623
0
        g.NavId = window->NavLastIds[0];
11624
0
        g.NavFocusScopeId = window->NavRootFocusScopeId;
11625
0
    }
11626
2
}
11627
11628
static ImVec2 ImGui::NavCalcPreferredRefPos()
11629
0
{
11630
0
    ImGuiContext& g = *GImGui;
11631
0
    ImGuiWindow* window = g.NavWindow;
11632
0
    if (g.NavDisableHighlight || !g.NavDisableMouseHover || !window)
11633
0
    {
11634
        // Mouse (we need a fallback in case the mouse becomes invalid after being used)
11635
        // The +1.0f offset when stored by OpenPopupEx() allows reopening this or another popup (same or another mouse button) while not moving the mouse, it is pretty standard.
11636
        // In theory we could move that +1.0f offset in OpenPopupEx()
11637
0
        ImVec2 p = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : g.MouseLastValidPos;
11638
0
        return ImVec2(p.x + 1.0f, p.y);
11639
0
    }
11640
0
    else
11641
0
    {
11642
        // When navigation is active and mouse is disabled, pick a position around the bottom left of the currently navigated item
11643
        // Take account of upcoming scrolling (maybe set mouse pos should be done in EndFrame?)
11644
0
        ImRect rect_rel = WindowRectRelToAbs(window, window->NavRectRel[g.NavLayer]);
11645
0
        if (window->LastFrameActive != g.FrameCount && (window->ScrollTarget.x != FLT_MAX || window->ScrollTarget.y != FLT_MAX))
11646
0
        {
11647
0
            ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
11648
0
            rect_rel.Translate(window->Scroll - next_scroll);
11649
0
        }
11650
0
        ImVec2 pos = ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
11651
0
        ImGuiViewport* viewport = window->Viewport;
11652
0
        return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
11653
0
    }
11654
0
}
11655
11656
float ImGui::GetNavTweakPressedAmount(ImGuiAxis axis)
11657
0
{
11658
0
    ImGuiContext& g = *GImGui;
11659
0
    float repeat_delay, repeat_rate;
11660
0
    GetTypematicRepeatRate(ImGuiInputFlags_RepeatRateNavTweak, &repeat_delay, &repeat_rate);
11661
11662
0
    ImGuiKey key_less, key_more;
11663
0
    if (g.NavInputSource == ImGuiInputSource_Gamepad)
11664
0
    {
11665
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadLeft : ImGuiKey_GamepadDpadUp;
11666
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_GamepadDpadRight : ImGuiKey_GamepadDpadDown;
11667
0
    }
11668
0
    else
11669
0
    {
11670
0
        key_less = (axis == ImGuiAxis_X) ? ImGuiKey_LeftArrow : ImGuiKey_UpArrow;
11671
0
        key_more = (axis == ImGuiAxis_X) ? ImGuiKey_RightArrow : ImGuiKey_DownArrow;
11672
0
    }
11673
0
    float amount = (float)GetKeyPressedAmount(key_more, repeat_delay, repeat_rate) - (float)GetKeyPressedAmount(key_less, repeat_delay, repeat_rate);
11674
0
    if (amount != 0.0f && IsKeyDown(key_less) && IsKeyDown(key_more)) // Cancel when opposite directions are held, regardless of repeat phase
11675
0
        amount = 0.0f;
11676
0
    return amount;
11677
0
}
11678
11679
static void ImGui::NavUpdate()
11680
34.4k
{
11681
34.4k
    ImGuiContext& g = *GImGui;
11682
34.4k
    ImGuiIO& io = g.IO;
11683
11684
34.4k
    io.WantSetMousePos = false;
11685
    //if (g.NavScoringDebugCount > 0) IMGUI_DEBUG_LOG_NAV("[nav] NavScoringDebugCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.NavScoringDebugCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
11686
11687
    // Set input source based on which keys are last pressed (as some features differs when used with Gamepad vs Keyboard)
11688
    // FIXME-NAV: Now that keys are separated maybe we can get rid of NavInputSource?
11689
34.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11690
34.4k
    const ImGuiKey nav_gamepad_keys_to_change_source[] = { ImGuiKey_GamepadFaceRight, ImGuiKey_GamepadFaceLeft, ImGuiKey_GamepadFaceUp, ImGuiKey_GamepadFaceDown, ImGuiKey_GamepadDpadRight, ImGuiKey_GamepadDpadLeft, ImGuiKey_GamepadDpadUp, ImGuiKey_GamepadDpadDown };
11691
34.4k
    if (nav_gamepad_active)
11692
0
        for (ImGuiKey key : nav_gamepad_keys_to_change_source)
11693
0
            if (IsKeyDown(key))
11694
0
                g.NavInputSource = ImGuiInputSource_Gamepad;
11695
34.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11696
34.4k
    const ImGuiKey nav_keyboard_keys_to_change_source[] = { ImGuiKey_Space, ImGuiKey_Enter, ImGuiKey_Escape, ImGuiKey_RightArrow, ImGuiKey_LeftArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow };
11697
34.4k
    if (nav_keyboard_active)
11698
34.4k
        for (ImGuiKey key : nav_keyboard_keys_to_change_source)
11699
241k
            if (IsKeyDown(key))
11700
9.95k
                g.NavInputSource = ImGuiInputSource_Keyboard;
11701
11702
    // Process navigation init request (select first/default focus)
11703
34.4k
    if (g.NavInitResultId != 0)
11704
0
        NavInitRequestApplyResult();
11705
34.4k
    g.NavInitRequest = false;
11706
34.4k
    g.NavInitRequestFromMove = false;
11707
34.4k
    g.NavInitResultId = 0;
11708
34.4k
    g.NavJustMovedToId = 0;
11709
11710
    // Process navigation move request
11711
34.4k
    if (g.NavMoveSubmitted)
11712
9
        NavMoveRequestApplyResult();
11713
34.4k
    g.NavTabbingCounter = 0;
11714
34.4k
    g.NavMoveSubmitted = g.NavMoveScoringItems = false;
11715
11716
    // Schedule mouse position update (will be done at the bottom of this function, after 1) processing all move requests and 2) updating scrolling)
11717
34.4k
    bool set_mouse_pos = false;
11718
34.4k
    if (g.NavMousePosDirty && g.NavIdIsAlive)
11719
44
        if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
11720
44
            set_mouse_pos = true;
11721
34.4k
    g.NavMousePosDirty = false;
11722
34.4k
    IM_ASSERT(g.NavLayer == ImGuiNavLayer_Main || g.NavLayer == ImGuiNavLayer_Menu);
11723
11724
    // Store our return window (for returning from Menu Layer to Main Layer) and clear it as soon as we step back in our own Layer 0
11725
34.4k
    if (g.NavWindow)
11726
1.31k
        NavSaveLastChildNavWindowIntoParent(g.NavWindow);
11727
34.4k
    if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
11728
53
        g.NavWindow->NavLastChildNavWindow = NULL;
11729
11730
    // Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
11731
34.4k
    NavUpdateWindowing();
11732
11733
    // Set output flags for user application
11734
34.4k
    io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
11735
34.4k
    io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
11736
11737
    // Process NavCancel input (to close a popup, get back to parent, clear focus)
11738
34.4k
    NavUpdateCancelRequest();
11739
11740
    // Process manual activation request
11741
34.4k
    g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavActivateInputId = 0;
11742
34.4k
    g.NavActivateFlags = ImGuiActivateFlags_None;
11743
34.4k
    if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11744
128
    {
11745
128
        const bool activate_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Space)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadActivate));
11746
128
        const bool activate_pressed = activate_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Space, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadActivate, false)));
11747
128
        const bool input_down = (nav_keyboard_active && IsKeyDown(ImGuiKey_Enter)) || (nav_gamepad_active && IsKeyDown(ImGuiKey_NavGamepadInput));
11748
128
        const bool input_pressed = input_down && ((nav_keyboard_active && IsKeyPressed(ImGuiKey_Enter, false)) || (nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadInput, false)));
11749
128
        if (g.ActiveId == 0 && activate_pressed)
11750
0
        {
11751
0
            g.NavActivateId = g.NavId;
11752
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferTweak;
11753
0
        }
11754
128
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && input_pressed)
11755
0
        {
11756
0
            g.NavActivateInputId = g.NavId;
11757
0
            g.NavActivateFlags = ImGuiActivateFlags_PreferInput;
11758
0
        }
11759
128
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
11760
0
            g.NavActivateDownId = g.NavId;
11761
128
        if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
11762
0
            g.NavActivatePressedId = g.NavId;
11763
128
    }
11764
34.4k
    if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
11765
0
        g.NavDisableHighlight = true;
11766
34.4k
    if (g.NavActivateId != 0)
11767
34.4k
        IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
11768
11769
    // Process programmatic activation request
11770
    // FIXME-NAV: Those should eventually be queued (unlike focus they don't cancel each others)
11771
34.4k
    if (g.NavNextActivateId != 0)
11772
0
    {
11773
0
        if (g.NavNextActivateFlags & ImGuiActivateFlags_PreferInput)
11774
0
            g.NavActivateInputId = g.NavNextActivateId;
11775
0
        else
11776
0
            g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavNextActivateId;
11777
0
        g.NavActivateFlags = g.NavNextActivateFlags;
11778
0
    }
11779
34.4k
    g.NavNextActivateId = 0;
11780
11781
    // Process move requests
11782
34.4k
    NavUpdateCreateMoveRequest();
11783
34.4k
    if (g.NavMoveDir == ImGuiDir_None)
11784
34.4k
        NavUpdateCreateTabbingRequest();
11785
34.4k
    NavUpdateAnyRequestFlag();
11786
34.4k
    g.NavIdIsAlive = false;
11787
11788
    // Scrolling
11789
34.4k
    if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
11790
1.31k
    {
11791
        // *Fallback* manual-scroll with Nav directional keys when window has no navigable item
11792
1.31k
        ImGuiWindow* window = g.NavWindow;
11793
1.31k
        const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
11794
1.31k
        const ImGuiDir move_dir = g.NavMoveDir;
11795
1.31k
        if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && move_dir != ImGuiDir_None)
11796
5
        {
11797
5
            if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
11798
0
                SetScrollX(window, ImFloor(window->Scroll.x + ((move_dir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
11799
5
            if (move_dir == ImGuiDir_Up || move_dir == ImGuiDir_Down)
11800
5
                SetScrollY(window, ImFloor(window->Scroll.y + ((move_dir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
11801
5
        }
11802
11803
        // *Normal* Manual scroll with LStick
11804
        // Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
11805
1.31k
        if (nav_gamepad_active)
11806
0
        {
11807
0
            const ImVec2 scroll_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
11808
0
            const float tweak_factor = IsKeyDown(ImGuiKey_NavGamepadTweakSlow) ? 1.0f / 10.0f : IsKeyDown(ImGuiKey_NavGamepadTweakFast) ? 10.0f : 1.0f;
11809
0
            if (scroll_dir.x != 0.0f && window->ScrollbarX)
11810
0
                SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed * tweak_factor));
11811
0
            if (scroll_dir.y != 0.0f)
11812
0
                SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed * tweak_factor));
11813
0
        }
11814
1.31k
    }
11815
11816
    // Always prioritize mouse highlight if navigation is disabled
11817
34.4k
    if (!nav_keyboard_active && !nav_gamepad_active)
11818
0
    {
11819
0
        g.NavDisableHighlight = true;
11820
0
        g.NavDisableMouseHover = set_mouse_pos = false;
11821
0
    }
11822
11823
    // Update mouse position if requested
11824
    // (This will take into account the possibility that a Scroll was queued in the window to offset our absolute mouse position before scroll has been applied)
11825
34.4k
    if (set_mouse_pos && (io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
11826
0
    {
11827
0
        io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
11828
0
        io.WantSetMousePos = true;
11829
        //IMGUI_DEBUG_LOG_IO("SetMousePos: (%.1f,%.1f)\n", io.MousePos.x, io.MousePos.y);
11830
0
    }
11831
11832
    // [DEBUG]
11833
34.4k
    g.NavScoringDebugCount = 0;
11834
#if IMGUI_DEBUG_NAV_RECTS
11835
    if (g.NavWindow)
11836
    {
11837
        ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
11838
        if (1) { for (int layer = 0; layer < 2; layer++) { ImRect r = WindowRectRelToAbs(g.NavWindow, g.NavWindow->NavRectRel[layer]); draw_list->AddRect(r.Min, r.Max, IM_COL32(255,200,0,255)); } } // [DEBUG]
11839
        if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
11840
    }
11841
#endif
11842
34.4k
}
11843
11844
void ImGui::NavInitRequestApplyResult()
11845
0
{
11846
    // In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
11847
0
    ImGuiContext& g = *GImGui;
11848
0
    if (!g.NavWindow)
11849
0
        return;
11850
11851
    // Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
11852
    // FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
11853
0
    IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: ApplyResult: NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
11854
0
    SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
11855
0
    g.NavIdIsAlive = true; // Mark as alive from previous frame as we got a result
11856
0
    if (g.NavInitRequestFromMove)
11857
0
        NavRestoreHighlightAfterMove();
11858
0
}
11859
11860
void ImGui::NavUpdateCreateMoveRequest()
11861
34.4k
{
11862
34.4k
    ImGuiContext& g = *GImGui;
11863
34.4k
    ImGuiIO& io = g.IO;
11864
34.4k
    ImGuiWindow* window = g.NavWindow;
11865
34.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
11866
34.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
11867
11868
34.4k
    if (g.NavMoveForwardToNextFrame && window != NULL)
11869
0
    {
11870
        // Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
11871
        // (preserve most state, which were already set by the NavMoveRequestForward() function)
11872
0
        IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
11873
0
        IM_ASSERT(g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded);
11874
0
        IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
11875
0
    }
11876
34.4k
    else
11877
34.4k
    {
11878
        // Initiate directional inputs request
11879
34.4k
        g.NavMoveDir = ImGuiDir_None;
11880
34.4k
        g.NavMoveFlags = ImGuiNavMoveFlags_None;
11881
34.4k
        g.NavMoveScrollFlags = ImGuiScrollFlags_None;
11882
34.4k
        if (window && !g.NavWindowingTarget && !(window->Flags & ImGuiWindowFlags_NoNavInputs))
11883
1.31k
        {
11884
1.31k
            const ImGuiInputFlags repeat_mode = ImGuiInputFlags_Repeat | (ImGuiInputFlags)ImGuiInputFlags_RepeatRateNavMove;
11885
1.31k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Left)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadLeft,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_LeftArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Left; }
11886
1.31k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadRight, ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_RightArrow, ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Right; }
11887
1.31k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Up)    && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadUp,    ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_UpArrow,    ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Up; }
11888
1.31k
            if (!IsActiveIdUsingNavDir(ImGuiDir_Down)  && ((nav_gamepad_active && IsKeyPressed(ImGuiKey_GamepadDpadDown,  ImGuiKeyOwner_None, repeat_mode)) || (nav_keyboard_active && IsKeyPressed(ImGuiKey_DownArrow,  ImGuiKeyOwner_None, repeat_mode)))) { g.NavMoveDir = ImGuiDir_Down; }
11889
1.31k
        }
11890
34.4k
        g.NavMoveClipDir = g.NavMoveDir;
11891
34.4k
        g.NavScoringNoClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
11892
34.4k
    }
11893
11894
    // Update PageUp/PageDown/Home/End scroll
11895
    // FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
11896
34.4k
    float scoring_rect_offset_y = 0.0f;
11897
34.4k
    if (window && g.NavMoveDir == ImGuiDir_None && nav_keyboard_active)
11898
1.29k
        scoring_rect_offset_y = NavUpdatePageUpPageDown();
11899
34.4k
    if (scoring_rect_offset_y != 0.0f)
11900
7
    {
11901
7
        g.NavScoringNoClipRect = window->InnerRect;
11902
7
        g.NavScoringNoClipRect.TranslateY(scoring_rect_offset_y);
11903
7
    }
11904
11905
    // [DEBUG] Always send a request
11906
#if IMGUI_DEBUG_NAV_SCORING
11907
    if (io.KeyCtrl && IsKeyPressed(ImGuiKey_C))
11908
        g.NavMoveDirForDebug = (ImGuiDir)((g.NavMoveDirForDebug + 1) & 3);
11909
    if (io.KeyCtrl && g.NavMoveDir == ImGuiDir_None)
11910
    {
11911
        g.NavMoveDir = g.NavMoveDirForDebug;
11912
        g.NavMoveFlags |= ImGuiNavMoveFlags_DebugNoResult;
11913
    }
11914
#endif
11915
11916
    // Submit
11917
34.4k
    g.NavMoveForwardToNextFrame = false;
11918
34.4k
    if (g.NavMoveDir != ImGuiDir_None)
11919
26
        NavMoveRequestSubmit(g.NavMoveDir, g.NavMoveClipDir, g.NavMoveFlags, g.NavMoveScrollFlags);
11920
11921
    // Moving with no reference triggers an init request (will be used as a fallback if the direction fails to find a match)
11922
34.4k
    if (g.NavMoveSubmitted && g.NavId == 0)
11923
14
    {
11924
14
        IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", window ? window->Name : "<NULL>", g.NavLayer);
11925
14
        g.NavInitRequest = g.NavInitRequestFromMove = true;
11926
14
        g.NavInitResultId = 0;
11927
14
        g.NavDisableHighlight = false;
11928
14
    }
11929
11930
    // When using gamepad, we project the reference nav bounding box into window visible area.
11931
    // This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad all movements are relative
11932
    // (can't focus a visible object like we can with the mouse).
11933
34.4k
    if (g.NavMoveSubmitted && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main && window != NULL)// && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded))
11934
0
    {
11935
0
        bool clamp_x = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapX)) == 0;
11936
0
        bool clamp_y = (g.NavMoveFlags & (ImGuiNavMoveFlags_LoopY | ImGuiNavMoveFlags_WrapY)) == 0;
11937
0
        ImRect inner_rect_rel = WindowRectAbsToRel(window, ImRect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1)));
11938
0
        if ((clamp_x || clamp_y) && !inner_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
11939
0
        {
11940
            //IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel for gamepad move\n");
11941
0
            float pad_x = ImMin(inner_rect_rel.GetWidth(), window->CalcFontSize() * 0.5f);
11942
0
            float pad_y = ImMin(inner_rect_rel.GetHeight(), window->CalcFontSize() * 0.5f); // Terrible approximation for the intent of starting navigation from first fully visible item
11943
0
            inner_rect_rel.Min.x = clamp_x ? (inner_rect_rel.Min.x + pad_x) : -FLT_MAX;
11944
0
            inner_rect_rel.Max.x = clamp_x ? (inner_rect_rel.Max.x - pad_x) : +FLT_MAX;
11945
0
            inner_rect_rel.Min.y = clamp_y ? (inner_rect_rel.Min.y + pad_y) : -FLT_MAX;
11946
0
            inner_rect_rel.Max.y = clamp_y ? (inner_rect_rel.Max.y - pad_y) : +FLT_MAX;
11947
0
            window->NavRectRel[g.NavLayer].ClipWithFull(inner_rect_rel);
11948
0
            g.NavId = 0;
11949
0
        }
11950
0
    }
11951
11952
    // For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
11953
34.4k
    ImRect scoring_rect;
11954
34.4k
    if (window != NULL)
11955
1.31k
    {
11956
1.31k
        ImRect nav_rect_rel = !window->NavRectRel[g.NavLayer].IsInverted() ? window->NavRectRel[g.NavLayer] : ImRect(0, 0, 0, 0);
11957
1.31k
        scoring_rect = WindowRectRelToAbs(window, nav_rect_rel);
11958
1.31k
        scoring_rect.TranslateY(scoring_rect_offset_y);
11959
1.31k
        scoring_rect.Min.x = ImMin(scoring_rect.Min.x + 1.0f, scoring_rect.Max.x);
11960
1.31k
        scoring_rect.Max.x = scoring_rect.Min.x;
11961
1.31k
        IM_ASSERT(!scoring_rect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allow us to remove extraneous ImFabs() calls in NavScoreItem().
11962
        //GetForegroundDrawList()->AddRect(scoring_rect.Min, scoring_rect.Max, IM_COL32(255,200,0,255)); // [DEBUG]
11963
        //if (!g.NavScoringNoClipRect.IsInverted()) { GetForegroundDrawList()->AddRect(g.NavScoringNoClipRect.Min, g.NavScoringNoClipRect.Max, IM_COL32(255, 200, 0, 255)); } // [DEBUG]
11964
1.31k
    }
11965
34.4k
    g.NavScoringRect = scoring_rect;
11966
34.4k
    g.NavScoringNoClipRect.Add(scoring_rect);
11967
34.4k
}
11968
11969
void ImGui::NavUpdateCreateTabbingRequest()
11970
34.4k
{
11971
34.4k
    ImGuiContext& g = *GImGui;
11972
34.4k
    ImGuiWindow* window = g.NavWindow;
11973
34.4k
    IM_ASSERT(g.NavMoveDir == ImGuiDir_None);
11974
34.4k
    if (window == NULL || g.NavWindowingTarget != NULL || (window->Flags & ImGuiWindowFlags_NoNavInputs))
11975
33.1k
        return;
11976
11977
1.29k
    const bool tab_pressed = IsKeyPressed(ImGuiKey_Tab, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat) && !g.IO.KeyCtrl && !g.IO.KeyAlt;
11978
1.29k
    if (!tab_pressed)
11979
1.29k
        return;
11980
11981
    // Initiate tabbing request
11982
    // (this is ALWAYS ENABLED, regardless of ImGuiConfigFlags_NavEnableKeyboard flag!)
11983
    // Initially this was designed to use counters and modulo arithmetic, but that could not work with unsubmitted items (list clipper). Instead we use a strategy close to other move requests.
11984
    // See NavProcessItemForTabbingRequest() for a description of the various forward/backward tabbing cases with and without wrapping.
11985
    //// FIXME: We use (g.ActiveId == 0) but (g.NavDisableHighlight == false) might be righter once we can tab through anything
11986
0
    g.NavTabbingDir = g.IO.KeyShift ? -1 : (g.ActiveId == 0) ? 0 : +1;
11987
0
    ImGuiScrollFlags scroll_flags = window->Appearing ? ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_AlwaysCenterY : ImGuiScrollFlags_KeepVisibleEdgeX | ImGuiScrollFlags_KeepVisibleEdgeY;
11988
0
    ImGuiDir clip_dir = (g.NavTabbingDir < 0) ? ImGuiDir_Up : ImGuiDir_Down;
11989
0
    NavMoveRequestSubmit(ImGuiDir_None, clip_dir, ImGuiNavMoveFlags_Tabbing, scroll_flags); // FIXME-NAV: Once we refactor tabbing, add LegacyApi flag to not activate non-inputable.
11990
0
    g.NavTabbingCounter = -1;
11991
0
}
11992
11993
// Apply result from previous frame navigation directional move request. Always called from NavUpdate()
11994
void ImGui::NavMoveRequestApplyResult()
11995
9
{
11996
9
    ImGuiContext& g = *GImGui;
11997
#if IMGUI_DEBUG_NAV_SCORING
11998
    if (g.NavMoveFlags & ImGuiNavMoveFlags_DebugNoResult) // [DEBUG] Scoring all items in NavWindow at all times
11999
        return;
12000
#endif
12001
12002
    // Select which result to use
12003
9
    ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : (g.NavMoveResultOther.ID != 0) ? &g.NavMoveResultOther : NULL;
12004
12005
    // Tabbing forward wrap
12006
9
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12007
0
        if ((g.NavTabbingCounter == 1 || g.NavTabbingDir == 0) && g.NavTabbingResultFirst.ID)
12008
0
            result = &g.NavTabbingResultFirst;
12009
12010
    // In a situation when there are no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
12011
9
    if (result == NULL)
12012
4
    {
12013
4
        if (g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing)
12014
0
            g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12015
4
        if (g.NavId != 0 && (g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12016
2
            NavRestoreHighlightAfterMove();
12017
4
        return;
12018
4
    }
12019
12020
    // PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
12021
5
    if (g.NavMoveFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
12022
5
        if (g.NavMoveResultLocalVisible.ID != 0 && g.NavMoveResultLocalVisible.ID != g.NavId)
12023
0
            result = &g.NavMoveResultLocalVisible;
12024
12025
    // Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
12026
5
    if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
12027
0
        if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
12028
0
            result = &g.NavMoveResultOther;
12029
5
    IM_ASSERT(g.NavWindow && result->Window);
12030
12031
    // Scroll to keep newly navigated item fully into view.
12032
5
    if (g.NavLayer == ImGuiNavLayer_Main)
12033
5
    {
12034
5
        if (g.NavMoveFlags & ImGuiNavMoveFlags_ScrollToEdgeY)
12035
0
        {
12036
            // FIXME: Should remove this
12037
0
            float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
12038
0
            SetScrollY(result->Window, scroll_target);
12039
0
        }
12040
5
        else
12041
5
        {
12042
5
            ImRect rect_abs = WindowRectRelToAbs(result->Window, result->RectRel);
12043
5
            ScrollToRectEx(result->Window, rect_abs, g.NavMoveScrollFlags);
12044
5
        }
12045
5
    }
12046
12047
5
    if (g.NavWindow != result->Window)
12048
0
    {
12049
0
        IMGUI_DEBUG_LOG_FOCUS("[focus] NavMoveRequest: SetNavWindow(\"%s\")\n", result->Window->Name);
12050
0
        g.NavWindow = result->Window;
12051
0
    }
12052
5
    if (g.ActiveId != result->ID)
12053
5
        ClearActiveID();
12054
5
    if (g.NavId != result->ID)
12055
0
    {
12056
        // Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
12057
0
        g.NavJustMovedToId = result->ID;
12058
0
        g.NavJustMovedToFocusScopeId = result->FocusScopeId;
12059
0
        g.NavJustMovedToKeyMods = g.NavMoveKeyMods;
12060
0
    }
12061
12062
    // Focus
12063
5
    IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
12064
5
    SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
12065
12066
    // Tabbing: Activates Inputable or Focus non-Inputable
12067
5
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_Tabbing) && (result->InFlags & ImGuiItemFlags_Inputable))
12068
0
    {
12069
0
        g.NavNextActivateId = result->ID;
12070
0
        g.NavNextActivateFlags = ImGuiActivateFlags_PreferInput | ImGuiActivateFlags_TryToPreserveState;
12071
0
        g.NavMoveFlags |= ImGuiNavMoveFlags_DontSetNavHighlight;
12072
0
    }
12073
12074
    // Activate
12075
5
    if (g.NavMoveFlags & ImGuiNavMoveFlags_Activate)
12076
0
    {
12077
0
        g.NavNextActivateId = result->ID;
12078
0
        g.NavNextActivateFlags = ImGuiActivateFlags_None;
12079
0
    }
12080
12081
    // Enable nav highlight
12082
5
    if ((g.NavMoveFlags & ImGuiNavMoveFlags_DontSetNavHighlight) == 0)
12083
5
        NavRestoreHighlightAfterMove();
12084
5
}
12085
12086
// Process NavCancel input (to close a popup, get back to parent, clear focus)
12087
// FIXME: In order to support e.g. Escape to clear a selection we'll need:
12088
// - either to store the equivalent of ActiveIdUsingKeyInputMask for a FocusScope and test for it.
12089
// - either to move most/all of those tests to the epilogue/end functions of the scope they are dealing with (e.g. exit child window in EndChild()) or in EndFrame(), to allow an earlier intercept
12090
static void ImGui::NavUpdateCancelRequest()
12091
34.4k
{
12092
34.4k
    ImGuiContext& g = *GImGui;
12093
34.4k
    const bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12094
34.4k
    const bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12095
34.4k
    if (!(nav_keyboard_active && IsKeyPressed(ImGuiKey_Escape, ImGuiKeyOwner_None)) && !(nav_gamepad_active && IsKeyPressed(ImGuiKey_NavGamepadCancel, ImGuiKeyOwner_None)))
12096
34.1k
        return;
12097
12098
274
    IMGUI_DEBUG_LOG_NAV("[nav] NavUpdateCancelRequest()\n");
12099
274
    if (g.ActiveId != 0)
12100
0
    {
12101
0
        ClearActiveID();
12102
0
    }
12103
274
    else if (g.NavLayer != ImGuiNavLayer_Main)
12104
0
    {
12105
        // Leave the "menu" layer
12106
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12107
0
        NavRestoreHighlightAfterMove();
12108
0
    }
12109
274
    else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
12110
39
    {
12111
        // Exit child window
12112
39
        ImGuiWindow* child_window = g.NavWindow;
12113
39
        ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
12114
39
        IM_ASSERT(child_window->ChildId != 0);
12115
39
        ImRect child_rect = child_window->Rect();
12116
39
        FocusWindow(parent_window);
12117
39
        SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, WindowRectAbsToRel(parent_window, child_rect));
12118
39
        NavRestoreHighlightAfterMove();
12119
39
    }
12120
235
    else if (g.OpenPopupStack.Size > 0 && g.OpenPopupStack.back().Window != NULL && !(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
12121
0
    {
12122
        // Close open popup/menu
12123
0
        ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
12124
0
    }
12125
235
    else
12126
235
    {
12127
        // Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
12128
235
        if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
12129
0
            g.NavWindow->NavLastIds[0] = 0;
12130
235
        g.NavId = 0;
12131
235
    }
12132
274
}
12133
12134
// Handle PageUp/PageDown/Home/End keys
12135
// Called from NavUpdateCreateMoveRequest() which will use our output to create a move request
12136
// FIXME-NAV: This doesn't work properly with NavFlattened siblings as we use NavWindow rectangle for reference
12137
// FIXME-NAV: how to get Home/End to aim at the beginning/end of a 2D grid?
12138
static float ImGui::NavUpdatePageUpPageDown()
12139
1.29k
{
12140
1.29k
    ImGuiContext& g = *GImGui;
12141
1.29k
    ImGuiWindow* window = g.NavWindow;
12142
1.29k
    if ((window->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL)
12143
0
        return 0.0f;
12144
12145
1.29k
    const bool page_up_held = IsKeyDown(ImGuiKey_PageUp, ImGuiKeyOwner_None);
12146
1.29k
    const bool page_down_held = IsKeyDown(ImGuiKey_PageDown, ImGuiKeyOwner_None);
12147
1.29k
    const bool home_pressed = IsKeyPressed(ImGuiKey_Home, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12148
1.29k
    const bool end_pressed = IsKeyPressed(ImGuiKey_End, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat);
12149
1.29k
    if (page_up_held == page_down_held && home_pressed == end_pressed) // Proceed if either (not both) are pressed, otherwise early out
12150
1.20k
        return 0.0f;
12151
12152
89
    if (g.NavLayer != ImGuiNavLayer_Main)
12153
0
        NavRestoreLayer(ImGuiNavLayer_Main);
12154
12155
89
    if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
12156
38
    {
12157
        // Fallback manual-scroll when window has no navigable item
12158
38
        if (IsKeyPressed(ImGuiKey_PageUp, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12159
0
            SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
12160
38
        else if (IsKeyPressed(ImGuiKey_PageDown, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat))
12161
3
            SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
12162
35
        else if (home_pressed)
12163
3
            SetScrollY(window, 0.0f);
12164
32
        else if (end_pressed)
12165
6
            SetScrollY(window, window->ScrollMax.y);
12166
38
    }
12167
51
    else
12168
51
    {
12169
51
        ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
12170
51
        const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
12171
51
        float nav_scoring_rect_offset_y = 0.0f;
12172
51
        if (IsKeyPressed(ImGuiKey_PageUp, true))
12173
0
        {
12174
0
            nav_scoring_rect_offset_y = -page_offset_y;
12175
0
            g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
12176
0
            g.NavMoveClipDir = ImGuiDir_Up;
12177
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12178
0
        }
12179
51
        else if (IsKeyPressed(ImGuiKey_PageDown, true))
12180
7
        {
12181
7
            nav_scoring_rect_offset_y = +page_offset_y;
12182
7
            g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
12183
7
            g.NavMoveClipDir = ImGuiDir_Down;
12184
7
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
12185
7
        }
12186
44
        else if (home_pressed)
12187
0
        {
12188
            // FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
12189
            // Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdgeY flag, we don't scroll immediately to avoid scrolling happening before nav result.
12190
            // Preserve current horizontal position if we have any.
12191
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = 0.0f;
12192
0
            if (nav_rect_rel.IsInverted())
12193
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12194
0
            g.NavMoveDir = ImGuiDir_Down;
12195
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12196
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12197
0
        }
12198
44
        else if (end_pressed)
12199
0
        {
12200
0
            nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ContentSize.y;
12201
0
            if (nav_rect_rel.IsInverted())
12202
0
                nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
12203
0
            g.NavMoveDir = ImGuiDir_Up;
12204
0
            g.NavMoveFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdgeY;
12205
            // FIXME-NAV: MoveClipDir left to _None, intentional?
12206
0
        }
12207
51
        return nav_scoring_rect_offset_y;
12208
51
    }
12209
38
    return 0.0f;
12210
89
}
12211
12212
static void ImGui::NavEndFrame()
12213
34.4k
{
12214
34.4k
    ImGuiContext& g = *GImGui;
12215
12216
    // Show CTRL+TAB list window
12217
34.4k
    if (g.NavWindowingTarget != NULL)
12218
0
        NavUpdateWindowingOverlay();
12219
12220
    // Perform wrap-around in menus
12221
    // FIXME-NAV: Wrap may need to apply a weight bias on the other axis. e.g. 4x4 grid with 2 last items missing on last item won't handle LoopY/WrapY correctly.
12222
    // FIXME-NAV: Wrap (not Loop) support could be handled by the scoring function and then WrapX would function without an extra frame.
12223
34.4k
    const ImGuiNavMoveFlags wanted_flags = ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX | ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY;
12224
34.4k
    if (g.NavWindow && NavMoveRequestButNoResultYet() && (g.NavMoveFlags & wanted_flags) && (g.NavMoveFlags & ImGuiNavMoveFlags_Forwarded) == 0)
12225
0
        NavUpdateCreateWrappingRequest();
12226
34.4k
}
12227
12228
static void ImGui::NavUpdateCreateWrappingRequest()
12229
0
{
12230
0
    ImGuiContext& g = *GImGui;
12231
0
    ImGuiWindow* window = g.NavWindow;
12232
12233
0
    bool do_forward = false;
12234
0
    ImRect bb_rel = window->NavRectRel[g.NavLayer];
12235
0
    ImGuiDir clip_dir = g.NavMoveDir;
12236
0
    const ImGuiNavMoveFlags move_flags = g.NavMoveFlags;
12237
0
    if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12238
0
    {
12239
0
        bb_rel.Min.x = bb_rel.Max.x = window->ContentSize.x + window->WindowPadding.x;
12240
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12241
0
        {
12242
0
            bb_rel.TranslateY(-bb_rel.GetHeight()); // Previous row
12243
0
            clip_dir = ImGuiDir_Up;
12244
0
        }
12245
0
        do_forward = true;
12246
0
    }
12247
0
    if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
12248
0
    {
12249
0
        bb_rel.Min.x = bb_rel.Max.x = -window->WindowPadding.x;
12250
0
        if (move_flags & ImGuiNavMoveFlags_WrapX)
12251
0
        {
12252
0
            bb_rel.TranslateY(+bb_rel.GetHeight()); // Next row
12253
0
            clip_dir = ImGuiDir_Down;
12254
0
        }
12255
0
        do_forward = true;
12256
0
    }
12257
0
    if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12258
0
    {
12259
0
        bb_rel.Min.y = bb_rel.Max.y = window->ContentSize.y + window->WindowPadding.y;
12260
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12261
0
        {
12262
0
            bb_rel.TranslateX(-bb_rel.GetWidth()); // Previous column
12263
0
            clip_dir = ImGuiDir_Left;
12264
0
        }
12265
0
        do_forward = true;
12266
0
    }
12267
0
    if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
12268
0
    {
12269
0
        bb_rel.Min.y = bb_rel.Max.y = -window->WindowPadding.y;
12270
0
        if (move_flags & ImGuiNavMoveFlags_WrapY)
12271
0
        {
12272
0
            bb_rel.TranslateX(+bb_rel.GetWidth()); // Next column
12273
0
            clip_dir = ImGuiDir_Right;
12274
0
        }
12275
0
        do_forward = true;
12276
0
    }
12277
0
    if (!do_forward)
12278
0
        return;
12279
0
    window->NavRectRel[g.NavLayer] = bb_rel;
12280
0
    NavMoveRequestForward(g.NavMoveDir, clip_dir, move_flags, g.NavMoveScrollFlags);
12281
0
}
12282
12283
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
12284
0
{
12285
0
    ImGuiContext& g = *GImGui;
12286
0
    IM_UNUSED(g);
12287
0
    int order = window->FocusOrder;
12288
0
    IM_ASSERT(window->RootWindow == window); // No child window (not testing _ChildWindow because of docking)
12289
0
    IM_ASSERT(g.WindowsFocusOrder[order] == window);
12290
0
    return order;
12291
0
}
12292
12293
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
12294
0
{
12295
0
    ImGuiContext& g = *GImGui;
12296
0
    for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
12297
0
        if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
12298
0
            return g.WindowsFocusOrder[i];
12299
0
    return NULL;
12300
0
}
12301
12302
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
12303
0
{
12304
0
    ImGuiContext& g = *GImGui;
12305
0
    IM_ASSERT(g.NavWindowingTarget);
12306
0
    if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
12307
0
        return;
12308
12309
0
    const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
12310
0
    ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
12311
0
    if (!window_target)
12312
0
        window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
12313
0
    if (window_target) // Don't reset windowing target if there's a single window in the list
12314
0
    {
12315
0
        g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
12316
0
        g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12317
0
    }
12318
0
    g.NavWindowingToggleLayer = false;
12319
0
}
12320
12321
// Windowing management mode
12322
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
12323
// Gamepad:  Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
12324
static void ImGui::NavUpdateWindowing()
12325
34.4k
{
12326
34.4k
    ImGuiContext& g = *GImGui;
12327
34.4k
    ImGuiIO& io = g.IO;
12328
12329
34.4k
    ImGuiWindow* apply_focus_window = NULL;
12330
34.4k
    bool apply_toggle_layer = false;
12331
12332
34.4k
    ImGuiWindow* modal_window = GetTopMostPopupModal();
12333
34.4k
    bool allow_windowing = (modal_window == NULL);
12334
34.4k
    if (!allow_windowing)
12335
0
        g.NavWindowingTarget = NULL;
12336
12337
    // Fade out
12338
34.4k
    if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
12339
0
    {
12340
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - io.DeltaTime * 10.0f, 0.0f);
12341
0
        if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
12342
0
            g.NavWindowingTargetAnim = NULL;
12343
0
    }
12344
12345
    // Start CTRL+Tab or Square+L/R window selection
12346
34.4k
    const bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
12347
34.4k
    const bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
12348
34.4k
    const bool keyboard_next_window = allow_windowing && g.ConfigNavWindowingKeyNext && Shortcut(g.ConfigNavWindowingKeyNext, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12349
34.4k
    const bool keyboard_prev_window = allow_windowing && g.ConfigNavWindowingKeyPrev && Shortcut(g.ConfigNavWindowingKeyPrev, ImGuiKeyOwner_None, ImGuiInputFlags_Repeat | ImGuiInputFlags_RouteAlways);
12350
34.4k
    const bool start_windowing_with_gamepad = allow_windowing && nav_gamepad_active && !g.NavWindowingTarget && IsKeyPressed(ImGuiKey_NavGamepadMenu, 0, ImGuiInputFlags_None);
12351
34.4k
    const bool start_windowing_with_keyboard = allow_windowing && !g.NavWindowingTarget && (keyboard_next_window || keyboard_prev_window); // Note: enabled even without NavEnableKeyboard!
12352
34.4k
    if (start_windowing_with_gamepad || start_windowing_with_keyboard)
12353
0
        if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
12354
0
        {
12355
0
            g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow;
12356
0
            g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
12357
0
            g.NavWindowingAccumDeltaPos = g.NavWindowingAccumDeltaSize = ImVec2(0.0f, 0.0f);
12358
0
            g.NavWindowingToggleLayer = start_windowing_with_gamepad ? true : false; // Gamepad starts toggling layer
12359
0
            g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
12360
0
        }
12361
12362
    // Gamepad update
12363
34.4k
    g.NavWindowingTimer += io.DeltaTime;
12364
34.4k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
12365
0
    {
12366
        // Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
12367
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
12368
12369
        // Select window to focus
12370
0
        const int focus_change_dir = (int)IsKeyPressed(ImGuiKey_GamepadL1) - (int)IsKeyPressed(ImGuiKey_GamepadR1);
12371
0
        if (focus_change_dir != 0)
12372
0
        {
12373
0
            NavUpdateWindowingHighlightWindow(focus_change_dir);
12374
0
            g.NavWindowingHighlightAlpha = 1.0f;
12375
0
        }
12376
12377
        // Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered top-most)
12378
0
        if (!IsKeyDown(ImGuiKey_NavGamepadMenu))
12379
0
        {
12380
0
            g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
12381
0
            if (g.NavWindowingToggleLayer && g.NavWindow)
12382
0
                apply_toggle_layer = true;
12383
0
            else if (!g.NavWindowingToggleLayer)
12384
0
                apply_focus_window = g.NavWindowingTarget;
12385
0
            g.NavWindowingTarget = NULL;
12386
0
        }
12387
0
    }
12388
12389
    // Keyboard: Focus
12390
34.4k
    if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Keyboard)
12391
0
    {
12392
        // Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
12393
0
        ImGuiKeyChord shared_mods = ((g.ConfigNavWindowingKeyNext ? g.ConfigNavWindowingKeyNext : ImGuiMod_Mask_) & (g.ConfigNavWindowingKeyPrev ? g.ConfigNavWindowingKeyPrev : ImGuiMod_Mask_)) & ImGuiMod_Mask_;
12394
0
        IM_ASSERT(shared_mods != 0); // Next/Prev shortcut currently needs a shared modifier to "hold", otherwise Prev actions would keep cycling between two windows.
12395
0
        g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
12396
0
        if (keyboard_next_window || keyboard_prev_window)
12397
0
            NavUpdateWindowingHighlightWindow(keyboard_next_window ? -1 : +1);
12398
0
        else if ((io.KeyMods & shared_mods) != shared_mods)
12399
0
            apply_focus_window = g.NavWindowingTarget;
12400
0
    }
12401
12402
    // Keyboard: Press and Release ALT to toggle menu layer
12403
    // - Testing that only Alt is tested prevents Alt+Shift or AltGR from toggling menu layer.
12404
    // - AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl). But even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
12405
34.4k
    if (nav_keyboard_active && IsKeyPressed(ImGuiMod_Alt, ImGuiKeyOwner_None))
12406
0
    {
12407
0
        g.NavWindowingToggleLayer = true;
12408
0
        g.NavInputSource = ImGuiInputSource_Keyboard;
12409
0
    }
12410
34.4k
    if (g.NavWindowingToggleLayer && g.NavInputSource == ImGuiInputSource_Keyboard)
12411
0
    {
12412
        // We cancel toggling nav layer when any text has been typed (generally while holding Alt). (See #370)
12413
        // We cancel toggling nav layer when other modifiers are pressed. (See #4439)
12414
        // We cancel toggling nav layer if an owner has claimed the key.
12415
0
        if (io.InputQueueCharacters.Size > 0 || io.KeyCtrl || io.KeyShift || io.KeySuper || TestKeyOwner(ImGuiMod_Alt, ImGuiKeyOwner_None) == false)
12416
0
            g.NavWindowingToggleLayer = false;
12417
12418
        // Apply layer toggle on release
12419
        // Important: as before version <18314 we lacked an explicit IO event for focus gain/loss, we also compare mouse validity to detect old backends clearing mouse pos on focus loss.
12420
0
        if (IsKeyReleased(ImGuiMod_Alt) && g.NavWindowingToggleLayer)
12421
0
            if (g.ActiveId == 0 || g.ActiveIdAllowOverlap)
12422
0
                if (IsMousePosValid(&io.MousePos) == IsMousePosValid(&io.MousePosPrev))
12423
0
                    apply_toggle_layer = true;
12424
0
        if (!IsKeyDown(ImGuiMod_Alt))
12425
0
            g.NavWindowingToggleLayer = false;
12426
0
    }
12427
12428
    // Move window
12429
34.4k
    if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
12430
0
    {
12431
0
        ImVec2 nav_move_dir;
12432
0
        if (g.NavInputSource == ImGuiInputSource_Keyboard && !io.KeyShift)
12433
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_LeftArrow, ImGuiKey_RightArrow, ImGuiKey_UpArrow, ImGuiKey_DownArrow);
12434
0
        if (g.NavInputSource == ImGuiInputSource_Gamepad)
12435
0
            nav_move_dir = GetKeyMagnitude2d(ImGuiKey_GamepadLStickLeft, ImGuiKey_GamepadLStickRight, ImGuiKey_GamepadLStickUp, ImGuiKey_GamepadLStickDown);
12436
0
        if (nav_move_dir.x != 0.0f || nav_move_dir.y != 0.0f)
12437
0
        {
12438
0
            const float NAV_MOVE_SPEED = 800.0f;
12439
0
            const float move_step = NAV_MOVE_SPEED * io.DeltaTime * ImMin(io.DisplayFramebufferScale.x, io.DisplayFramebufferScale.y);
12440
0
            g.NavWindowingAccumDeltaPos += nav_move_dir * move_step;
12441
0
            g.NavDisableMouseHover = true;
12442
0
            ImVec2 accum_floored = ImFloor(g.NavWindowingAccumDeltaPos);
12443
0
            if (accum_floored.x != 0.0f || accum_floored.y != 0.0f)
12444
0
            {
12445
0
                ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindowDockTree;
12446
0
                SetWindowPos(moving_window, moving_window->Pos + accum_floored, ImGuiCond_Always);
12447
0
                g.NavWindowingAccumDeltaPos -= accum_floored;
12448
0
            }
12449
0
        }
12450
0
    }
12451
12452
    // Apply final focus
12453
34.4k
    if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
12454
0
    {
12455
0
        ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
12456
0
        ClearActiveID();
12457
0
        NavRestoreHighlightAfterMove();
12458
0
        apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
12459
0
        ClosePopupsOverWindow(apply_focus_window, false);
12460
0
        FocusWindow(apply_focus_window);
12461
0
        if (apply_focus_window->NavLastIds[0] == 0)
12462
0
            NavInitWindow(apply_focus_window, false);
12463
12464
        // If the window has ONLY a menu layer (no main layer), select it directly
12465
        // Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
12466
        // so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
12467
        // the target window as already been previewed once.
12468
        // FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
12469
        // we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
12470
        // won't be valid.
12471
0
        if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
12472
0
            g.NavLayer = ImGuiNavLayer_Menu;
12473
12474
        // Request OS level focus
12475
0
        if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
12476
0
            g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
12477
0
    }
12478
34.4k
    if (apply_focus_window)
12479
0
        g.NavWindowingTarget = NULL;
12480
12481
    // Apply menu/layer toggle
12482
34.4k
    if (apply_toggle_layer && g.NavWindow)
12483
0
    {
12484
0
        ClearActiveID();
12485
12486
        // Move to parent menu if necessary
12487
0
        ImGuiWindow* new_nav_window = g.NavWindow;
12488
0
        while (new_nav_window->ParentWindow
12489
0
            && (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
12490
0
            && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
12491
0
            && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
12492
0
            new_nav_window = new_nav_window->ParentWindow;
12493
0
        if (new_nav_window != g.NavWindow)
12494
0
        {
12495
0
            ImGuiWindow* old_nav_window = g.NavWindow;
12496
0
            FocusWindow(new_nav_window);
12497
0
            new_nav_window->NavLastChildNavWindow = old_nav_window;
12498
0
        }
12499
12500
        // Toggle layer
12501
0
        const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
12502
0
        if (new_nav_layer != g.NavLayer)
12503
0
        {
12504
            // Reinitialize navigation when entering menu bar with the Alt key (FIXME: could be a properly of the layer?)
12505
0
            const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
12506
0
            if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
12507
0
                g.NavWindow->NavLastIds[new_nav_layer] = 0;
12508
0
            NavRestoreLayer(new_nav_layer);
12509
0
            NavRestoreHighlightAfterMove();
12510
0
        }
12511
0
    }
12512
34.4k
}
12513
12514
// Window has already passed the IsWindowNavFocusable()
12515
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
12516
0
{
12517
0
    if (window->Flags & ImGuiWindowFlags_Popup)
12518
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingPopup);
12519
0
    if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
12520
0
        return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingMainMenuBar);
12521
0
    if (window->DockNodeAsHost)
12522
0
        return "(Dock node)"; // Not normally shown to user.
12523
0
    return ImGui::LocalizeGetMsg(ImGuiLocKey_WindowingUntitled);
12524
0
}
12525
12526
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
12527
void ImGui::NavUpdateWindowingOverlay()
12528
0
{
12529
0
    ImGuiContext& g = *GImGui;
12530
0
    IM_ASSERT(g.NavWindowingTarget != NULL);
12531
12532
0
    if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
12533
0
        return;
12534
12535
0
    if (g.NavWindowingListWindow == NULL)
12536
0
        g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
12537
0
    const ImGuiViewport* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ GetMainViewport();
12538
0
    SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
12539
0
    SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
12540
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
12541
0
    Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
12542
0
    for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
12543
0
    {
12544
0
        ImGuiWindow* window = g.WindowsFocusOrder[n];
12545
0
        IM_ASSERT(window != NULL); // Fix static analyzers
12546
0
        if (!IsWindowNavFocusable(window))
12547
0
            continue;
12548
0
        const char* label = window->Name;
12549
0
        if (label == FindRenderedTextEnd(label))
12550
0
            label = GetFallbackWindowNameForWindowingList(window);
12551
0
        Selectable(label, g.NavWindowingTarget == window);
12552
0
    }
12553
0
    End();
12554
0
    PopStyleVar();
12555
0
}
12556
12557
12558
//-----------------------------------------------------------------------------
12559
// [SECTION] DRAG AND DROP
12560
//-----------------------------------------------------------------------------
12561
12562
bool ImGui::IsDragDropActive()
12563
0
{
12564
0
    ImGuiContext& g = *GImGui;
12565
0
    return g.DragDropActive;
12566
0
}
12567
12568
void ImGui::ClearDragDrop()
12569
44
{
12570
44
    ImGuiContext& g = *GImGui;
12571
44
    g.DragDropActive = false;
12572
44
    g.DragDropPayload.Clear();
12573
44
    g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
12574
44
    g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
12575
44
    g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
12576
44
    g.DragDropAcceptFrameCount = -1;
12577
12578
44
    g.DragDropPayloadBufHeap.clear();
12579
44
    memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12580
44
}
12581
12582
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
12583
// If the item has an identifier:
12584
// - This assume/require the item to be activated (typically via ButtonBehavior).
12585
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
12586
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
12587
// If the item has no identifier:
12588
// - Currently always assume left mouse button.
12589
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
12590
89
{
12591
89
    ImGuiContext& g = *GImGui;
12592
89
    ImGuiWindow* window = g.CurrentWindow;
12593
12594
    // FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
12595
    // in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
12596
89
    ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
12597
12598
89
    bool source_drag_active = false;
12599
89
    ImGuiID source_id = 0;
12600
89
    ImGuiID source_parent_id = 0;
12601
89
    if (!(flags & ImGuiDragDropFlags_SourceExtern))
12602
89
    {
12603
89
        source_id = g.LastItemData.ID;
12604
89
        if (source_id != 0)
12605
89
        {
12606
            // Common path: items with ID
12607
89
            if (g.ActiveId != source_id)
12608
0
                return false;
12609
89
            if (g.ActiveIdMouseButton != -1)
12610
0
                mouse_button = g.ActiveIdMouseButton;
12611
89
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12612
0
                return false;
12613
89
            g.ActiveIdAllowOverlap = false;
12614
89
        }
12615
0
        else
12616
0
        {
12617
            // Uncommon path: items without ID
12618
0
            if (g.IO.MouseDown[mouse_button] == false || window->SkipItems)
12619
0
                return false;
12620
0
            if ((g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
12621
0
                return false;
12622
12623
            // If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
12624
            // A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag.
12625
0
            if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
12626
0
            {
12627
0
                IM_ASSERT(0);
12628
0
                return false;
12629
0
            }
12630
12631
            // Magic fallback to handle items with no assigned ID, e.g. Text(), Image()
12632
            // We build a throwaway ID based on current ID stack + relative AABB of items in window.
12633
            // THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING/RESIZINGG OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
12634
            // We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
12635
            // Rely on keeping other window->LastItemXXX fields intact.
12636
0
            source_id = g.LastItemData.ID = window->GetIDFromRectangle(g.LastItemData.Rect);
12637
0
            KeepAliveID(source_id);
12638
0
            bool is_hovered = ItemHoverable(g.LastItemData.Rect, source_id);
12639
0
            if (is_hovered && g.IO.MouseClicked[mouse_button])
12640
0
            {
12641
0
                SetActiveID(source_id, window);
12642
0
                FocusWindow(window);
12643
0
            }
12644
0
            if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
12645
0
                g.ActiveIdAllowOverlap = is_hovered;
12646
0
        }
12647
89
        if (g.ActiveId != source_id)
12648
0
            return false;
12649
89
        source_parent_id = window->IDStack.back();
12650
89
        source_drag_active = IsMouseDragging(mouse_button);
12651
12652
        // Disable navigation and key inputs while dragging + cancel existing request if any
12653
89
        SetActiveIdUsingAllKeyboardKeys();
12654
89
    }
12655
0
    else
12656
0
    {
12657
0
        window = NULL;
12658
0
        source_id = ImHashStr("#SourceExtern");
12659
0
        source_drag_active = true;
12660
0
    }
12661
12662
89
    if (source_drag_active)
12663
75
    {
12664
75
        if (!g.DragDropActive)
12665
22
        {
12666
22
            IM_ASSERT(source_id != 0);
12667
22
            ClearDragDrop();
12668
22
            ImGuiPayload& payload = g.DragDropPayload;
12669
22
            payload.SourceId = source_id;
12670
22
            payload.SourceParentId = source_parent_id;
12671
22
            g.DragDropActive = true;
12672
22
            g.DragDropSourceFlags = flags;
12673
22
            g.DragDropMouseButton = mouse_button;
12674
22
            if (payload.SourceId == g.ActiveId)
12675
22
                g.ActiveIdNoClearOnFocusLoss = true;
12676
22
        }
12677
75
        g.DragDropSourceFrameCount = g.FrameCount;
12678
75
        g.DragDropWithinSource = true;
12679
12680
75
        if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12681
0
        {
12682
            // Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
12683
            // We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
12684
0
            BeginTooltip();
12685
0
            if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
12686
0
            {
12687
0
                ImGuiWindow* tooltip_window = g.CurrentWindow;
12688
0
                tooltip_window->Hidden = tooltip_window->SkipItems = true;
12689
0
                tooltip_window->HiddenFramesCanSkipItems = 1;
12690
0
            }
12691
0
        }
12692
12693
75
        if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
12694
75
            g.LastItemData.StatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
12695
12696
75
        return true;
12697
75
    }
12698
14
    return false;
12699
89
}
12700
12701
void ImGui::EndDragDropSource()
12702
75
{
12703
75
    ImGuiContext& g = *GImGui;
12704
75
    IM_ASSERT(g.DragDropActive);
12705
75
    IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
12706
12707
75
    if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
12708
0
        EndTooltip();
12709
12710
    // Discard the drag if have not called SetDragDropPayload()
12711
75
    if (g.DragDropPayload.DataFrameCount == -1)
12712
0
        ClearDragDrop();
12713
75
    g.DragDropWithinSource = false;
12714
75
}
12715
12716
// Use 'cond' to choose to submit payload on drag start or every frame
12717
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
12718
75
{
12719
75
    ImGuiContext& g = *GImGui;
12720
75
    ImGuiPayload& payload = g.DragDropPayload;
12721
75
    if (cond == 0)
12722
75
        cond = ImGuiCond_Always;
12723
12724
75
    IM_ASSERT(type != NULL);
12725
75
    IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
12726
75
    IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
12727
75
    IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
12728
75
    IM_ASSERT(payload.SourceId != 0);                               // Not called between BeginDragDropSource() and EndDragDropSource()
12729
12730
75
    if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
12731
75
    {
12732
        // Copy payload
12733
75
        ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
12734
75
        g.DragDropPayloadBufHeap.resize(0);
12735
75
        if (data_size > sizeof(g.DragDropPayloadBufLocal))
12736
0
        {
12737
            // Store in heap
12738
0
            g.DragDropPayloadBufHeap.resize((int)data_size);
12739
0
            payload.Data = g.DragDropPayloadBufHeap.Data;
12740
0
            memcpy(payload.Data, data, data_size);
12741
0
        }
12742
75
        else if (data_size > 0)
12743
75
        {
12744
            // Store locally
12745
75
            memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
12746
75
            payload.Data = g.DragDropPayloadBufLocal;
12747
75
            memcpy(payload.Data, data, data_size);
12748
75
        }
12749
0
        else
12750
0
        {
12751
0
            payload.Data = NULL;
12752
0
        }
12753
75
        payload.DataSize = (int)data_size;
12754
75
    }
12755
75
    payload.DataFrameCount = g.FrameCount;
12756
12757
    // Return whether the payload has been accepted
12758
75
    return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
12759
75
}
12760
12761
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
12762
140
{
12763
140
    ImGuiContext& g = *GImGui;
12764
140
    if (!g.DragDropActive)
12765
0
        return false;
12766
12767
140
    ImGuiWindow* window = g.CurrentWindow;
12768
140
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12769
140
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree)
12770
136
        return false;
12771
4
    IM_ASSERT(id != 0);
12772
4
    if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
12773
0
        return false;
12774
4
    if (window->SkipItems)
12775
0
        return false;
12776
12777
4
    IM_ASSERT(g.DragDropWithinTarget == false);
12778
4
    g.DragDropTargetRect = bb;
12779
4
    g.DragDropTargetId = id;
12780
4
    g.DragDropWithinTarget = true;
12781
4
    return true;
12782
4
}
12783
12784
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
12785
// 1) we use LastItemRectHoveredRect which handles items that push a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
12786
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
12787
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
12788
bool ImGui::BeginDragDropTarget()
12789
0
{
12790
0
    ImGuiContext& g = *GImGui;
12791
0
    if (!g.DragDropActive)
12792
0
        return false;
12793
12794
0
    ImGuiWindow* window = g.CurrentWindow;
12795
0
    if (!(g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HoveredRect))
12796
0
        return false;
12797
0
    ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
12798
0
    if (hovered_window == NULL || window->RootWindowDockTree != hovered_window->RootWindowDockTree || window->SkipItems)
12799
0
        return false;
12800
12801
0
    const ImRect& display_rect = (g.LastItemData.StatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? g.LastItemData.DisplayRect : g.LastItemData.Rect;
12802
0
    ImGuiID id = g.LastItemData.ID;
12803
0
    if (id == 0)
12804
0
    {
12805
0
        id = window->GetIDFromRectangle(display_rect);
12806
0
        KeepAliveID(id);
12807
0
    }
12808
0
    if (g.DragDropPayload.SourceId == id)
12809
0
        return false;
12810
12811
0
    IM_ASSERT(g.DragDropWithinTarget == false);
12812
0
    g.DragDropTargetRect = display_rect;
12813
0
    g.DragDropTargetId = id;
12814
0
    g.DragDropWithinTarget = true;
12815
0
    return true;
12816
0
}
12817
12818
bool ImGui::IsDragDropPayloadBeingAccepted()
12819
34
{
12820
34
    ImGuiContext& g = *GImGui;
12821
34
    return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
12822
34
}
12823
12824
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
12825
4
{
12826
4
    ImGuiContext& g = *GImGui;
12827
4
    ImGuiWindow* window = g.CurrentWindow;
12828
4
    ImGuiPayload& payload = g.DragDropPayload;
12829
4
    IM_ASSERT(g.DragDropActive);                        // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
12830
4
    IM_ASSERT(payload.DataFrameCount != -1);            // Forgot to call EndDragDropTarget() ?
12831
4
    if (type != NULL && !payload.IsDataType(type))
12832
0
        return NULL;
12833
12834
    // Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
12835
    // NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
12836
4
    const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
12837
4
    ImRect r = g.DragDropTargetRect;
12838
4
    float r_surface = r.GetWidth() * r.GetHeight();
12839
4
    if (r_surface <= g.DragDropAcceptIdCurrRectSurface)
12840
4
    {
12841
4
        g.DragDropAcceptFlags = flags;
12842
4
        g.DragDropAcceptIdCurr = g.DragDropTargetId;
12843
4
        g.DragDropAcceptIdCurrRectSurface = r_surface;
12844
4
    }
12845
12846
    // Render default drop visuals
12847
4
    payload.Preview = was_accepted_previously;
12848
4
    flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that live for 1 frame)
12849
4
    if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
12850
0
        window->DrawList->AddRect(r.Min - ImVec2(3.5f,3.5f), r.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12851
12852
4
    g.DragDropAcceptFrameCount = g.FrameCount;
12853
4
    payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
12854
4
    if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
12855
0
        return NULL;
12856
12857
4
    return &payload;
12858
4
}
12859
12860
// FIXME-DRAGDROP: Settle on a proper default visuals for drop target.
12861
void ImGui::RenderDragDropTargetRect(const ImRect& bb)
12862
0
{
12863
0
    GetWindowDrawList()->AddRect(bb.Min - ImVec2(3.5f, 3.5f), bb.Max + ImVec2(3.5f, 3.5f), GetColorU32(ImGuiCol_DragDropTarget), 0.0f, 0, 2.0f);
12864
0
}
12865
12866
const ImGuiPayload* ImGui::GetDragDropPayload()
12867
0
{
12868
0
    ImGuiContext& g = *GImGui;
12869
0
    return (g.DragDropActive && g.DragDropPayload.DataFrameCount != -1) ? &g.DragDropPayload : NULL;
12870
0
}
12871
12872
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
12873
void ImGui::EndDragDropTarget()
12874
4
{
12875
4
    ImGuiContext& g = *GImGui;
12876
4
    IM_ASSERT(g.DragDropActive);
12877
4
    IM_ASSERT(g.DragDropWithinTarget);
12878
4
    g.DragDropWithinTarget = false;
12879
4
}
12880
12881
//-----------------------------------------------------------------------------
12882
// [SECTION] LOGGING/CAPTURING
12883
//-----------------------------------------------------------------------------
12884
// All text output from the interface can be captured into tty/file/clipboard.
12885
// By default, tree nodes are automatically opened during logging.
12886
//-----------------------------------------------------------------------------
12887
12888
// Pass text data straight to log (without being displayed)
12889
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
12890
0
{
12891
0
    if (g.LogFile)
12892
0
    {
12893
0
        g.LogBuffer.Buf.resize(0);
12894
0
        g.LogBuffer.appendfv(fmt, args);
12895
0
        ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
12896
0
    }
12897
0
    else
12898
0
    {
12899
0
        g.LogBuffer.appendfv(fmt, args);
12900
0
    }
12901
0
}
12902
12903
void ImGui::LogText(const char* fmt, ...)
12904
0
{
12905
0
    ImGuiContext& g = *GImGui;
12906
0
    if (!g.LogEnabled)
12907
0
        return;
12908
12909
0
    va_list args;
12910
0
    va_start(args, fmt);
12911
0
    LogTextV(g, fmt, args);
12912
0
    va_end(args);
12913
0
}
12914
12915
void ImGui::LogTextV(const char* fmt, va_list args)
12916
0
{
12917
0
    ImGuiContext& g = *GImGui;
12918
0
    if (!g.LogEnabled)
12919
0
        return;
12920
12921
0
    LogTextV(g, fmt, args);
12922
0
}
12923
12924
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
12925
// We split text into individual lines to add current tree level padding
12926
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
12927
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
12928
0
{
12929
0
    ImGuiContext& g = *GImGui;
12930
0
    ImGuiWindow* window = g.CurrentWindow;
12931
12932
0
    const char* prefix = g.LogNextPrefix;
12933
0
    const char* suffix = g.LogNextSuffix;
12934
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12935
12936
0
    if (!text_end)
12937
0
        text_end = FindRenderedTextEnd(text, text_end);
12938
12939
0
    const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
12940
0
    if (ref_pos)
12941
0
        g.LogLinePosY = ref_pos->y;
12942
0
    if (log_new_line)
12943
0
    {
12944
0
        LogText(IM_NEWLINE);
12945
0
        g.LogLineFirstItem = true;
12946
0
    }
12947
12948
0
    if (prefix)
12949
0
        LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
12950
12951
    // Re-adjust padding if we have popped out of our starting depth
12952
0
    if (g.LogDepthRef > window->DC.TreeDepth)
12953
0
        g.LogDepthRef = window->DC.TreeDepth;
12954
0
    const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
12955
12956
0
    const char* text_remaining = text;
12957
0
    for (;;)
12958
0
    {
12959
        // Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
12960
        // We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
12961
0
        const char* line_start = text_remaining;
12962
0
        const char* line_end = ImStreolRange(line_start, text_end);
12963
0
        const bool is_last_line = (line_end == text_end);
12964
0
        if (line_start != line_end || !is_last_line)
12965
0
        {
12966
0
            const int line_length = (int)(line_end - line_start);
12967
0
            const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
12968
0
            LogText("%*s%.*s", indentation, "", line_length, line_start);
12969
0
            g.LogLineFirstItem = false;
12970
0
            if (*line_end == '\n')
12971
0
            {
12972
0
                LogText(IM_NEWLINE);
12973
0
                g.LogLineFirstItem = true;
12974
0
            }
12975
0
        }
12976
0
        if (is_last_line)
12977
0
            break;
12978
0
        text_remaining = line_end + 1;
12979
0
    }
12980
12981
0
    if (suffix)
12982
0
        LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
12983
0
}
12984
12985
// Start logging/capturing text output
12986
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
12987
0
{
12988
0
    ImGuiContext& g = *GImGui;
12989
0
    ImGuiWindow* window = g.CurrentWindow;
12990
0
    IM_ASSERT(g.LogEnabled == false);
12991
0
    IM_ASSERT(g.LogFile == NULL);
12992
0
    IM_ASSERT(g.LogBuffer.empty());
12993
0
    g.LogEnabled = true;
12994
0
    g.LogType = type;
12995
0
    g.LogNextPrefix = g.LogNextSuffix = NULL;
12996
0
    g.LogDepthRef = window->DC.TreeDepth;
12997
0
    g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
12998
0
    g.LogLinePosY = FLT_MAX;
12999
0
    g.LogLineFirstItem = true;
13000
0
}
13001
13002
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
13003
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
13004
0
{
13005
0
    ImGuiContext& g = *GImGui;
13006
0
    g.LogNextPrefix = prefix;
13007
0
    g.LogNextSuffix = suffix;
13008
0
}
13009
13010
void ImGui::LogToTTY(int auto_open_depth)
13011
0
{
13012
0
    ImGuiContext& g = *GImGui;
13013
0
    if (g.LogEnabled)
13014
0
        return;
13015
0
    IM_UNUSED(auto_open_depth);
13016
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13017
0
    LogBegin(ImGuiLogType_TTY, auto_open_depth);
13018
0
    g.LogFile = stdout;
13019
0
#endif
13020
0
}
13021
13022
// Start logging/capturing text output to given file
13023
void ImGui::LogToFile(int auto_open_depth, const char* filename)
13024
0
{
13025
0
    ImGuiContext& g = *GImGui;
13026
0
    if (g.LogEnabled)
13027
0
        return;
13028
13029
    // FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
13030
    // be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
13031
    // By opening the file in binary mode "ab" we have consistent output everywhere.
13032
0
    if (!filename)
13033
0
        filename = g.IO.LogFilename;
13034
0
    if (!filename || !filename[0])
13035
0
        return;
13036
0
    ImFileHandle f = ImFileOpen(filename, "ab");
13037
0
    if (!f)
13038
0
    {
13039
0
        IM_ASSERT(0);
13040
0
        return;
13041
0
    }
13042
13043
0
    LogBegin(ImGuiLogType_File, auto_open_depth);
13044
0
    g.LogFile = f;
13045
0
}
13046
13047
// Start logging/capturing text output to clipboard
13048
void ImGui::LogToClipboard(int auto_open_depth)
13049
0
{
13050
0
    ImGuiContext& g = *GImGui;
13051
0
    if (g.LogEnabled)
13052
0
        return;
13053
0
    LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
13054
0
}
13055
13056
void ImGui::LogToBuffer(int auto_open_depth)
13057
0
{
13058
0
    ImGuiContext& g = *GImGui;
13059
0
    if (g.LogEnabled)
13060
0
        return;
13061
0
    LogBegin(ImGuiLogType_Buffer, auto_open_depth);
13062
0
}
13063
13064
void ImGui::LogFinish()
13065
68.8k
{
13066
68.8k
    ImGuiContext& g = *GImGui;
13067
68.8k
    if (!g.LogEnabled)
13068
68.8k
        return;
13069
13070
0
    LogText(IM_NEWLINE);
13071
0
    switch (g.LogType)
13072
0
    {
13073
0
    case ImGuiLogType_TTY:
13074
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13075
0
        fflush(g.LogFile);
13076
0
#endif
13077
0
        break;
13078
0
    case ImGuiLogType_File:
13079
0
        ImFileClose(g.LogFile);
13080
0
        break;
13081
0
    case ImGuiLogType_Buffer:
13082
0
        break;
13083
0
    case ImGuiLogType_Clipboard:
13084
0
        if (!g.LogBuffer.empty())
13085
0
            SetClipboardText(g.LogBuffer.begin());
13086
0
        break;
13087
0
    case ImGuiLogType_None:
13088
0
        IM_ASSERT(0);
13089
0
        break;
13090
0
    }
13091
13092
0
    g.LogEnabled = false;
13093
0
    g.LogType = ImGuiLogType_None;
13094
0
    g.LogFile = NULL;
13095
0
    g.LogBuffer.clear();
13096
0
}
13097
13098
// Helper to display logging buttons
13099
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
13100
void ImGui::LogButtons()
13101
0
{
13102
0
    ImGuiContext& g = *GImGui;
13103
13104
0
    PushID("LogButtons");
13105
0
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
13106
0
    const bool log_to_tty = Button("Log To TTY"); SameLine();
13107
#else
13108
    const bool log_to_tty = false;
13109
#endif
13110
0
    const bool log_to_file = Button("Log To File"); SameLine();
13111
0
    const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
13112
0
    PushAllowKeyboardFocus(false);
13113
0
    SetNextItemWidth(80.0f);
13114
0
    SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
13115
0
    PopAllowKeyboardFocus();
13116
0
    PopID();
13117
13118
    // Start logging at the end of the function so that the buttons don't appear in the log
13119
0
    if (log_to_tty)
13120
0
        LogToTTY();
13121
0
    if (log_to_file)
13122
0
        LogToFile();
13123
0
    if (log_to_clipboard)
13124
0
        LogToClipboard();
13125
0
}
13126
13127
13128
//-----------------------------------------------------------------------------
13129
// [SECTION] SETTINGS
13130
//-----------------------------------------------------------------------------
13131
// - UpdateSettings() [Internal]
13132
// - MarkIniSettingsDirty() [Internal]
13133
// - FindSettingsHandler() [Internal]
13134
// - ClearIniSettings() [Internal]
13135
// - LoadIniSettingsFromDisk()
13136
// - LoadIniSettingsFromMemory()
13137
// - SaveIniSettingsToDisk()
13138
// - SaveIniSettingsToMemory()
13139
//-----------------------------------------------------------------------------
13140
// - CreateNewWindowSettings() [Internal]
13141
// - FindWindowSettingsByID() [Internal]
13142
// - FindWindowSettingsByWindow() [Internal]
13143
// - ClearWindowSettings() [Internal]
13144
// - WindowSettingsHandler_***() [Internal]
13145
//-----------------------------------------------------------------------------
13146
13147
// Called by NewFrame()
13148
void ImGui::UpdateSettings()
13149
34.4k
{
13150
    // Load settings on first frame (if not explicitly loaded manually before)
13151
34.4k
    ImGuiContext& g = *GImGui;
13152
34.4k
    if (!g.SettingsLoaded)
13153
1
    {
13154
1
        IM_ASSERT(g.SettingsWindows.empty());
13155
1
        if (g.IO.IniFilename)
13156
0
            LoadIniSettingsFromDisk(g.IO.IniFilename);
13157
1
        g.SettingsLoaded = true;
13158
1
    }
13159
13160
    // Save settings (with a delay after the last modification, so we don't spam disk too much)
13161
34.4k
    if (g.SettingsDirtyTimer > 0.0f)
13162
4.50k
    {
13163
4.50k
        g.SettingsDirtyTimer -= g.IO.DeltaTime;
13164
4.50k
        if (g.SettingsDirtyTimer <= 0.0f)
13165
15
        {
13166
15
            if (g.IO.IniFilename != NULL)
13167
0
                SaveIniSettingsToDisk(g.IO.IniFilename);
13168
15
            else
13169
15
                g.IO.WantSaveIniSettings = true;  // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
13170
15
            g.SettingsDirtyTimer = 0.0f;
13171
15
        }
13172
4.50k
    }
13173
34.4k
}
13174
13175
void ImGui::MarkIniSettingsDirty()
13176
0
{
13177
0
    ImGuiContext& g = *GImGui;
13178
0
    if (g.SettingsDirtyTimer <= 0.0f)
13179
0
        g.SettingsDirtyTimer = g.IO.IniSavingRate;
13180
0
}
13181
13182
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
13183
1.48k
{
13184
1.48k
    ImGuiContext& g = *GImGui;
13185
1.48k
    if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
13186
497
        if (g.SettingsDirtyTimer <= 0.0f)
13187
15
            g.SettingsDirtyTimer = g.IO.IniSavingRate;
13188
1.48k
}
13189
13190
void ImGui::AddSettingsHandler(const ImGuiSettingsHandler* handler)
13191
2
{
13192
2
    ImGuiContext& g = *GImGui;
13193
2
    IM_ASSERT(FindSettingsHandler(handler->TypeName) == NULL);
13194
2
    g.SettingsHandlers.push_back(*handler);
13195
2
}
13196
13197
void ImGui::RemoveSettingsHandler(const char* type_name)
13198
0
{
13199
0
    ImGuiContext& g = *GImGui;
13200
0
    if (ImGuiSettingsHandler* handler = FindSettingsHandler(type_name))
13201
0
        g.SettingsHandlers.erase(handler);
13202
0
}
13203
13204
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
13205
2
{
13206
2
    ImGuiContext& g = *GImGui;
13207
2
    const ImGuiID type_hash = ImHashStr(type_name);
13208
3
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13209
1
        if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
13210
0
            return &g.SettingsHandlers[handler_n];
13211
2
    return NULL;
13212
2
}
13213
13214
// Clear all settings (windows, tables, docking etc.)
13215
void ImGui::ClearIniSettings()
13216
0
{
13217
0
    ImGuiContext& g = *GImGui;
13218
0
    g.SettingsIniData.clear();
13219
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13220
0
        if (g.SettingsHandlers[handler_n].ClearAllFn)
13221
0
            g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
13222
0
}
13223
13224
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
13225
0
{
13226
0
    size_t file_data_size = 0;
13227
0
    char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
13228
0
    if (!file_data)
13229
0
        return;
13230
0
    if (file_data_size > 0)
13231
0
        LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
13232
0
    IM_FREE(file_data);
13233
0
}
13234
13235
// Zero-tolerance, no error reporting, cheap .ini parsing
13236
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
13237
0
{
13238
0
    ImGuiContext& g = *GImGui;
13239
0
    IM_ASSERT(g.Initialized);
13240
    //IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
13241
    //IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
13242
13243
    // For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
13244
    // For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
13245
0
    if (ini_size == 0)
13246
0
        ini_size = strlen(ini_data);
13247
0
    g.SettingsIniData.Buf.resize((int)ini_size + 1);
13248
0
    char* const buf = g.SettingsIniData.Buf.Data;
13249
0
    char* const buf_end = buf + ini_size;
13250
0
    memcpy(buf, ini_data, ini_size);
13251
0
    buf_end[0] = 0;
13252
13253
    // Call pre-read handlers
13254
    // Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
13255
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13256
0
        if (g.SettingsHandlers[handler_n].ReadInitFn)
13257
0
            g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
13258
13259
0
    void* entry_data = NULL;
13260
0
    ImGuiSettingsHandler* entry_handler = NULL;
13261
13262
0
    char* line_end = NULL;
13263
0
    for (char* line = buf; line < buf_end; line = line_end + 1)
13264
0
    {
13265
        // Skip new lines markers, then find end of the line
13266
0
        while (*line == '\n' || *line == '\r')
13267
0
            line++;
13268
0
        line_end = line;
13269
0
        while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
13270
0
            line_end++;
13271
0
        line_end[0] = 0;
13272
0
        if (line[0] == ';')
13273
0
            continue;
13274
0
        if (line[0] == '[' && line_end > line && line_end[-1] == ']')
13275
0
        {
13276
            // Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
13277
0
            line_end[-1] = 0;
13278
0
            const char* name_end = line_end - 1;
13279
0
            const char* type_start = line + 1;
13280
0
            char* type_end = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
13281
0
            const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
13282
0
            if (!type_end || !name_start)
13283
0
                continue;
13284
0
            *type_end = 0; // Overwrite first ']'
13285
0
            name_start++;  // Skip second '['
13286
0
            entry_handler = FindSettingsHandler(type_start);
13287
0
            entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
13288
0
        }
13289
0
        else if (entry_handler != NULL && entry_data != NULL)
13290
0
        {
13291
            // Let type handler parse the line
13292
0
            entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
13293
0
        }
13294
0
    }
13295
0
    g.SettingsLoaded = true;
13296
13297
    // [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
13298
0
    memcpy(buf, ini_data, ini_size);
13299
13300
    // Call post-read handlers
13301
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13302
0
        if (g.SettingsHandlers[handler_n].ApplyAllFn)
13303
0
            g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
13304
0
}
13305
13306
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
13307
0
{
13308
0
    ImGuiContext& g = *GImGui;
13309
0
    g.SettingsDirtyTimer = 0.0f;
13310
0
    if (!ini_filename)
13311
0
        return;
13312
13313
0
    size_t ini_data_size = 0;
13314
0
    const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
13315
0
    ImFileHandle f = ImFileOpen(ini_filename, "wt");
13316
0
    if (!f)
13317
0
        return;
13318
0
    ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
13319
0
    ImFileClose(f);
13320
0
}
13321
13322
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
13323
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
13324
0
{
13325
0
    ImGuiContext& g = *GImGui;
13326
0
    g.SettingsDirtyTimer = 0.0f;
13327
0
    g.SettingsIniData.Buf.resize(0);
13328
0
    g.SettingsIniData.Buf.push_back(0);
13329
0
    for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
13330
0
    {
13331
0
        ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
13332
0
        handler->WriteAllFn(&g, handler, &g.SettingsIniData);
13333
0
    }
13334
0
    if (out_size)
13335
0
        *out_size = (size_t)g.SettingsIniData.size();
13336
0
    return g.SettingsIniData.c_str();
13337
0
}
13338
13339
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
13340
0
{
13341
0
    ImGuiContext& g = *GImGui;
13342
13343
0
#if !IMGUI_DEBUG_INI_SETTINGS
13344
    // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
13345
    // Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
13346
0
    if (const char* p = strstr(name, "###"))
13347
0
        name = p;
13348
0
#endif
13349
0
    const size_t name_len = strlen(name);
13350
13351
    // Allocate chunk
13352
0
    const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
13353
0
    ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
13354
0
    IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
13355
0
    settings->ID = ImHashStr(name, name_len);
13356
0
    memcpy(settings->GetName(), name, name_len + 1);   // Store with zero terminator
13357
13358
0
    return settings;
13359
0
}
13360
13361
// We don't provide a FindWindowSettingsByName() because Docking system doesn't always hold on names.
13362
// This is called once per window .ini entry + once per newly instantiated window.
13363
ImGuiWindowSettings* ImGui::FindWindowSettingsByID(ImGuiID id)
13364
2
{
13365
2
    ImGuiContext& g = *GImGui;
13366
2
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13367
0
        if (settings->ID == id)
13368
0
            return settings;
13369
2
    return NULL;
13370
2
}
13371
13372
// This is faster if you are holding on a Window already as we don't need to perform a search.
13373
ImGuiWindowSettings* ImGui::FindWindowSettingsByWindow(ImGuiWindow* window)
13374
2
{
13375
2
    ImGuiContext& g = *GImGui;
13376
2
    if (window->SettingsOffset != -1)
13377
0
        return g.SettingsWindows.ptr_from_offset(window->SettingsOffset);
13378
2
    return FindWindowSettingsByID(window->ID);
13379
2
}
13380
13381
// This will revert window to its initial state, including enabling the ImGuiCond_FirstUseEver/ImGuiCond_Once conditions once more.
13382
void ImGui::ClearWindowSettings(const char* name)
13383
0
{
13384
    //IMGUI_DEBUG_LOG("ClearWindowSettings('%s')\n", name);
13385
0
    ImGuiContext& g = *GImGui;
13386
0
    ImGuiWindow* window = FindWindowByName(name);
13387
0
    if (window != NULL)
13388
0
    {
13389
0
        window->Flags |= ImGuiWindowFlags_NoSavedSettings;
13390
0
        InitOrLoadWindowSettings(window, NULL);
13391
0
        if (window->DockId != 0)
13392
0
            DockContextProcessUndockWindow(&g, window, true);
13393
0
    }
13394
0
    if (ImGuiWindowSettings* settings = window ? FindWindowSettingsByWindow(window) : FindWindowSettingsByID(ImHashStr(name)))
13395
0
        settings->WantDelete = true;
13396
0
}
13397
13398
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13399
0
{
13400
0
    ImGuiContext& g = *ctx;
13401
0
    for (int i = 0; i != g.Windows.Size; i++)
13402
0
        g.Windows[i]->SettingsOffset = -1;
13403
0
    g.SettingsWindows.clear();
13404
0
}
13405
13406
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
13407
0
{
13408
0
    ImGuiID id = ImHashStr(name);
13409
0
    ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByID(id);
13410
0
    if (settings)
13411
0
        *settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
13412
0
    else
13413
0
        settings = ImGui::CreateNewWindowSettings(name);
13414
0
    settings->ID = id;
13415
0
    settings->WantApply = true;
13416
0
    return (void*)settings;
13417
0
}
13418
13419
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
13420
0
{
13421
0
    ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
13422
0
    int x, y;
13423
0
    int i;
13424
0
    ImU32 u1;
13425
0
    if (sscanf(line, "Pos=%i,%i", &x, &y) == 2)             { settings->Pos = ImVec2ih((short)x, (short)y); }
13426
0
    else if (sscanf(line, "Size=%i,%i", &x, &y) == 2)       { settings->Size = ImVec2ih((short)x, (short)y); }
13427
0
    else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1)   { settings->ViewportId = u1; }
13428
0
    else if (sscanf(line, "ViewportPos=%i,%i", &x, &y) == 2){ settings->ViewportPos = ImVec2ih((short)x, (short)y); }
13429
0
    else if (sscanf(line, "Collapsed=%d", &i) == 1)         { settings->Collapsed = (i != 0); }
13430
0
    else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2)  { settings->DockId = u1; settings->DockOrder = (short)i; }
13431
0
    else if (sscanf(line, "DockId=0x%X", &u1) == 1)         { settings->DockId = u1; settings->DockOrder = -1; }
13432
0
    else if (sscanf(line, "ClassId=0x%X", &u1) == 1)        { settings->ClassId = u1; }
13433
0
}
13434
13435
// Apply to existing windows (if any)
13436
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
13437
0
{
13438
0
    ImGuiContext& g = *ctx;
13439
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13440
0
        if (settings->WantApply)
13441
0
        {
13442
0
            if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
13443
0
                ApplyWindowSettings(window, settings);
13444
0
            settings->WantApply = false;
13445
0
        }
13446
0
}
13447
13448
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
13449
0
{
13450
    // Gather data from windows that were active during this session
13451
    // (if a window wasn't opened in this session we preserve its settings)
13452
0
    ImGuiContext& g = *ctx;
13453
0
    for (int i = 0; i != g.Windows.Size; i++)
13454
0
    {
13455
0
        ImGuiWindow* window = g.Windows[i];
13456
0
        if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
13457
0
            continue;
13458
13459
0
        ImGuiWindowSettings* settings = ImGui::FindWindowSettingsByWindow(window);
13460
0
        if (!settings)
13461
0
        {
13462
0
            settings = ImGui::CreateNewWindowSettings(window->Name);
13463
0
            window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
13464
0
        }
13465
0
        IM_ASSERT(settings->ID == window->ID);
13466
0
        settings->Pos = ImVec2ih(window->Pos - window->ViewportPos);
13467
0
        settings->Size = ImVec2ih(window->SizeFull);
13468
0
        settings->ViewportId = window->ViewportId;
13469
0
        settings->ViewportPos = ImVec2ih(window->ViewportPos);
13470
0
        IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
13471
0
        settings->DockId = window->DockId;
13472
0
        settings->ClassId = window->WindowClass.ClassId;
13473
0
        settings->DockOrder = window->DockOrder;
13474
0
        settings->Collapsed = window->Collapsed;
13475
0
        settings->WantDelete = false;
13476
0
    }
13477
13478
    // Write to text buffer
13479
0
    buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
13480
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
13481
0
    {
13482
0
        if (settings->WantDelete)
13483
0
            continue;
13484
0
        const char* settings_name = settings->GetName();
13485
0
        buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
13486
0
        if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13487
0
        {
13488
0
            buf->appendf("ViewportPos=%d,%d\n", settings->ViewportPos.x, settings->ViewportPos.y);
13489
0
            buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
13490
0
        }
13491
0
        if (settings->Pos.x != 0 || settings->Pos.y != 0 || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
13492
0
            buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
13493
0
        if (settings->Size.x != 0 || settings->Size.y != 0)
13494
0
            buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
13495
0
        buf->appendf("Collapsed=%d\n", settings->Collapsed);
13496
0
        if (settings->DockId != 0)
13497
0
        {
13498
            //buf->appendf("TabId=0x%08X\n", ImHashStr("#TAB", 4, settings->ID)); // window->TabId: this is not read back but writing it makes "debugging" the .ini data easier.
13499
0
            if (settings->DockOrder == -1)
13500
0
                buf->appendf("DockId=0x%08X\n", settings->DockId);
13501
0
            else
13502
0
                buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
13503
0
            if (settings->ClassId != 0)
13504
0
                buf->appendf("ClassId=0x%08X\n", settings->ClassId);
13505
0
        }
13506
0
        buf->append("\n");
13507
0
    }
13508
0
}
13509
13510
13511
//-----------------------------------------------------------------------------
13512
// [SECTION] LOCALIZATION
13513
//-----------------------------------------------------------------------------
13514
13515
void ImGui::LocalizeRegisterEntries(const ImGuiLocEntry* entries, int count)
13516
1
{
13517
1
    ImGuiContext& g = *GImGui;
13518
9
    for (int n = 0; n < count; n++)
13519
8
        g.LocalizationTable[entries[n].Key] = entries[n].Text;
13520
1
}
13521
13522
13523
//-----------------------------------------------------------------------------
13524
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
13525
//-----------------------------------------------------------------------------
13526
// - GetMainViewport()
13527
// - FindViewportByID()
13528
// - FindViewportByPlatformHandle()
13529
// - SetCurrentViewport() [Internal]
13530
// - SetWindowViewport() [Internal]
13531
// - GetWindowAlwaysWantOwnViewport() [Internal]
13532
// - UpdateTryMergeWindowIntoHostViewport() [Internal]
13533
// - UpdateTryMergeWindowIntoHostViewports() [Internal]
13534
// - TranslateWindowsInViewport() [Internal]
13535
// - ScaleWindowsInViewport() [Internal]
13536
// - FindHoveredViewportFromPlatformWindowStack() [Internal]
13537
// - UpdateViewportsNewFrame() [Internal]
13538
// - UpdateViewportsEndFrame() [Internal]
13539
// - AddUpdateViewport() [Internal]
13540
// - WindowSelectViewport() [Internal]
13541
// - WindowSyncOwnedViewport() [Internal]
13542
// - UpdatePlatformWindows()
13543
// - RenderPlatformWindowsDefault()
13544
// - FindPlatformMonitorForPos() [Internal]
13545
// - FindPlatformMonitorForRect() [Internal]
13546
// - UpdateViewportPlatformMonitor() [Internal]
13547
// - DestroyPlatformWindow() [Internal]
13548
// - DestroyPlatformWindows()
13549
//-----------------------------------------------------------------------------
13550
13551
ImGuiViewport* ImGui::GetMainViewport()
13552
71.9k
{
13553
71.9k
    ImGuiContext& g = *GImGui;
13554
71.9k
    return g.Viewports[0];
13555
71.9k
}
13556
13557
// FIXME: This leaks access to viewports not listed in PlatformIO.Viewports[]. Problematic? (#4236)
13558
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
13559
34.4k
{
13560
34.4k
    ImGuiContext& g = *GImGui;
13561
34.4k
    for (int n = 0; n < g.Viewports.Size; n++)
13562
34.4k
        if (g.Viewports[n]->ID == id)
13563
34.4k
            return g.Viewports[n];
13564
0
    return NULL;
13565
34.4k
}
13566
13567
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
13568
0
{
13569
0
    ImGuiContext& g = *GImGui;
13570
0
    for (int i = 0; i != g.Viewports.Size; i++)
13571
0
        if (g.Viewports[i]->PlatformHandle == platform_handle)
13572
0
            return g.Viewports[i];
13573
0
    return NULL;
13574
0
}
13575
13576
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
13577
143k
{
13578
143k
    ImGuiContext& g = *GImGui;
13579
143k
    (void)current_window;
13580
13581
143k
    if (viewport)
13582
109k
        viewport->LastFrameActive = g.FrameCount;
13583
143k
    if (g.CurrentViewport == viewport)
13584
74.9k
        return;
13585
68.8k
    g.CurrentDpiScale = viewport ? viewport->DpiScale : 1.0f;
13586
68.8k
    g.CurrentViewport = viewport;
13587
    //IMGUI_DEBUG_LOG_VIEWPORT("[viewport] SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
13588
13589
    // Notify platform layer of viewport changes
13590
    // FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
13591
68.8k
    if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
13592
0
        g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
13593
68.8k
}
13594
13595
void ImGui::SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13596
71.9k
{
13597
    // Abandon viewport
13598
71.9k
    if (window->ViewportOwned && window->Viewport->Window == window)
13599
0
        window->Viewport->Size = ImVec2(0.0f, 0.0f);
13600
13601
71.9k
    window->Viewport = viewport;
13602
71.9k
    window->ViewportId = viewport->ID;
13603
71.9k
    window->ViewportOwned = (viewport->Window == window);
13604
71.9k
}
13605
13606
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
13607
0
{
13608
    // Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protrude and create their own.
13609
0
    ImGuiContext& g = *GImGui;
13610
0
    if (g.IO.ConfigViewportsNoAutoMerge || (window->WindowClass.ViewportFlagsOverrideSet & ImGuiViewportFlags_NoAutoMerge))
13611
0
        if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
13612
0
            if (!window->DockIsActive)
13613
0
                if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip)) == 0)
13614
0
                    if ((window->Flags & ImGuiWindowFlags_Popup) == 0 || (window->Flags & ImGuiWindowFlags_Modal) != 0)
13615
0
                        return true;
13616
0
    return false;
13617
0
}
13618
13619
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
13620
0
{
13621
0
    ImGuiContext& g = *GImGui;
13622
0
    if (window->Viewport == viewport)
13623
0
        return false;
13624
0
    if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) == 0)
13625
0
        return false;
13626
0
    if ((viewport->Flags & ImGuiViewportFlags_Minimized) != 0)
13627
0
        return false;
13628
0
    if (!viewport->GetMainRect().Contains(window->Rect()))
13629
0
        return false;
13630
0
    if (GetWindowAlwaysWantOwnViewport(window))
13631
0
        return false;
13632
13633
    // FIXME: Can't use g.WindowsFocusOrder[] for root windows only as we care about Z order. If we maintained a DisplayOrder along with FocusOrder we could..
13634
0
    for (int n = 0; n < g.Windows.Size; n++)
13635
0
    {
13636
0
        ImGuiWindow* window_behind = g.Windows[n];
13637
0
        if (window_behind == window)
13638
0
            break;
13639
0
        if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
13640
0
            if (window_behind->Viewport->GetMainRect().Overlaps(window->Rect()))
13641
0
                return false;
13642
0
    }
13643
13644
    // Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
13645
0
    ImGuiViewportP* old_viewport = window->Viewport;
13646
0
    if (window->ViewportOwned)
13647
0
        for (int n = 0; n < g.Windows.Size; n++)
13648
0
            if (g.Windows[n]->Viewport == old_viewport)
13649
0
                SetWindowViewport(g.Windows[n], viewport);
13650
0
    SetWindowViewport(window, viewport);
13651
0
    BringWindowToDisplayFront(window);
13652
13653
0
    return true;
13654
0
}
13655
13656
// FIXME: handle 0 to N host viewports
13657
static bool ImGui::UpdateTryMergeWindowIntoHostViewports(ImGuiWindow* window)
13658
0
{
13659
0
    ImGuiContext& g = *GImGui;
13660
0
    return UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
13661
0
}
13662
13663
// Translate Dear ImGui windows when a Host Viewport has been moved
13664
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13665
void ImGui::TranslateWindowsInViewport(ImGuiViewportP* viewport, const ImVec2& old_pos, const ImVec2& new_pos)
13666
0
{
13667
0
    ImGuiContext& g = *GImGui;
13668
0
    IM_ASSERT(viewport->Window == NULL && (viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows));
13669
13670
    // 1) We test if ImGuiConfigFlags_ViewportsEnable was just toggled, which allows us to conveniently
13671
    // translate imgui windows from OS-window-local to absolute coordinates or vice-versa.
13672
    // 2) If it's not going to fit into the new size, keep it at same absolute position.
13673
    // One problem with this is that most Win32 applications doesn't update their render while dragging,
13674
    // and so the window will appear to teleport when releasing the mouse.
13675
0
    const bool translate_all_windows = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != (g.ConfigFlagsLastFrame & ImGuiConfigFlags_ViewportsEnable);
13676
0
    ImRect test_still_fit_rect(old_pos, old_pos + viewport->Size);
13677
0
    ImVec2 delta_pos = new_pos - old_pos;
13678
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++) // FIXME-OPT
13679
0
        if (translate_all_windows || (g.Windows[window_n]->Viewport == viewport && test_still_fit_rect.Contains(g.Windows[window_n]->Rect())))
13680
0
            TranslateWindow(g.Windows[window_n], delta_pos);
13681
0
}
13682
13683
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
13684
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
13685
0
{
13686
0
    ImGuiContext& g = *GImGui;
13687
0
    if (viewport->Window)
13688
0
    {
13689
0
        ScaleWindow(viewport->Window, scale);
13690
0
    }
13691
0
    else
13692
0
    {
13693
0
        for (int i = 0; i != g.Windows.Size; i++)
13694
0
            if (g.Windows[i]->Viewport == viewport)
13695
0
                ScaleWindow(g.Windows[i], scale);
13696
0
    }
13697
0
}
13698
13699
// If the backend doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
13700
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13701
// B) It requires Platform_GetWindowFocus to be implemented by backend.
13702
ImGuiViewportP* ImGui::FindHoveredViewportFromPlatformWindowStack(const ImVec2& mouse_platform_pos)
13703
0
{
13704
0
    ImGuiContext& g = *GImGui;
13705
0
    ImGuiViewportP* best_candidate = NULL;
13706
0
    for (int n = 0; n < g.Viewports.Size; n++)
13707
0
    {
13708
0
        ImGuiViewportP* viewport = g.Viewports[n];
13709
0
        if (!(viewport->Flags & (ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_Minimized)) && viewport->GetMainRect().Contains(mouse_platform_pos))
13710
0
            if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
13711
0
                best_candidate = viewport;
13712
0
    }
13713
0
    return best_candidate;
13714
0
}
13715
13716
// Update viewports and monitor infos
13717
// Note that this is running even if 'ImGuiConfigFlags_ViewportsEnable' is not set, in order to clear unused viewports (if any) and update monitor info.
13718
static void ImGui::UpdateViewportsNewFrame()
13719
34.4k
{
13720
34.4k
    ImGuiContext& g = *GImGui;
13721
34.4k
    IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
13722
13723
    // Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
13724
34.4k
    const bool viewports_enabled = (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable) != 0;
13725
34.4k
    if (viewports_enabled)
13726
0
    {
13727
0
        for (int n = 0; n < g.Viewports.Size; n++)
13728
0
        {
13729
0
            ImGuiViewportP* viewport = g.Viewports[n];
13730
0
            const bool platform_funcs_available = viewport->PlatformWindowCreated;
13731
0
            if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
13732
0
            {
13733
0
                bool minimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
13734
0
                if (minimized)
13735
0
                    viewport->Flags |= ImGuiViewportFlags_Minimized;
13736
0
                else
13737
0
                    viewport->Flags &= ~ImGuiViewportFlags_Minimized;
13738
0
            }
13739
0
        }
13740
0
    }
13741
13742
    // Create/update main viewport with current platform position.
13743
    // FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
13744
34.4k
    ImGuiViewportP* main_viewport = g.Viewports[0];
13745
34.4k
    IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
13746
34.4k
    IM_ASSERT(main_viewport->Window == NULL);
13747
34.4k
    ImVec2 main_viewport_pos = viewports_enabled ? g.PlatformIO.Platform_GetWindowPos(main_viewport) : ImVec2(0.0f, 0.0f);
13748
34.4k
    ImVec2 main_viewport_size = g.IO.DisplaySize;
13749
34.4k
    if (viewports_enabled && (main_viewport->Flags & ImGuiViewportFlags_Minimized))
13750
0
    {
13751
0
        main_viewport_pos = main_viewport->Pos;    // Preserve last pos/size when minimized (FIXME: We don't do the same for Size outside of the viewport path)
13752
0
        main_viewport_size = main_viewport->Size;
13753
0
    }
13754
34.4k
    AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_pos, main_viewport_size, ImGuiViewportFlags_OwnedByApp | ImGuiViewportFlags_CanHostOtherWindows);
13755
13756
34.4k
    g.CurrentDpiScale = 0.0f;
13757
34.4k
    g.CurrentViewport = NULL;
13758
34.4k
    g.MouseViewport = NULL;
13759
68.8k
    for (int n = 0; n < g.Viewports.Size; n++)
13760
34.4k
    {
13761
34.4k
        ImGuiViewportP* viewport = g.Viewports[n];
13762
34.4k
        viewport->Idx = n;
13763
13764
        // Erase unused viewports
13765
34.4k
        if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
13766
0
        {
13767
0
            DestroyViewport(viewport);
13768
0
            n--;
13769
0
            continue;
13770
0
        }
13771
13772
34.4k
        const bool platform_funcs_available = viewport->PlatformWindowCreated;
13773
34.4k
        if (viewports_enabled)
13774
0
        {
13775
            // Update Position and Size (from Platform Window to ImGui) if requested.
13776
            // We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
13777
0
            if (!(viewport->Flags & ImGuiViewportFlags_Minimized) && platform_funcs_available)
13778
0
            {
13779
                // Viewport->WorkPos and WorkSize will be updated below
13780
0
                if (viewport->PlatformRequestMove)
13781
0
                    viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
13782
0
                if (viewport->PlatformRequestResize)
13783
0
                    viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
13784
0
            }
13785
0
        }
13786
13787
        // Update/copy monitor info
13788
34.4k
        UpdateViewportPlatformMonitor(viewport);
13789
13790
        // Lock down space taken by menu bars and status bars, reset the offset for functions like BeginMainMenuBar() to alter them again.
13791
34.4k
        viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
13792
34.4k
        viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
13793
34.4k
        viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
13794
34.4k
        viewport->UpdateWorkRect();
13795
13796
        // Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
13797
34.4k
        viewport->Alpha = 1.0f;
13798
13799
        // Translate Dear ImGui windows when a Host Viewport has been moved
13800
        // (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
13801
34.4k
        const ImVec2 viewport_delta_pos = viewport->Pos - viewport->LastPos;
13802
34.4k
        if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta_pos.x != 0.0f || viewport_delta_pos.y != 0.0f))
13803
0
            TranslateWindowsInViewport(viewport, viewport->LastPos, viewport->Pos);
13804
13805
        // Update DPI scale
13806
34.4k
        float new_dpi_scale;
13807
34.4k
        if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
13808
0
            new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
13809
34.4k
        else if (viewport->PlatformMonitor != -1)
13810
0
            new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13811
34.4k
        else
13812
34.4k
            new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
13813
34.4k
        if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
13814
0
        {
13815
0
            float scale_factor = new_dpi_scale / viewport->DpiScale;
13816
0
            if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
13817
0
                ScaleWindowsInViewport(viewport, scale_factor);
13818
            //if (viewport == GetMainViewport())
13819
            //    g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
13820
13821
            // Scale our window moving pivot so that the window will rescale roughly around the mouse position.
13822
            // FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
13823
            // (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
13824
            //if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
13825
            //    g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
13826
0
        }
13827
34.4k
        viewport->DpiScale = new_dpi_scale;
13828
34.4k
    }
13829
13830
    // Update fallback monitor
13831
34.4k
    if (g.PlatformIO.Monitors.Size == 0)
13832
34.4k
    {
13833
34.4k
        ImGuiPlatformMonitor* monitor = &g.FallbackMonitor;
13834
34.4k
        monitor->MainPos = main_viewport->Pos;
13835
34.4k
        monitor->MainSize = main_viewport->Size;
13836
34.4k
        monitor->WorkPos = main_viewport->WorkPos;
13837
34.4k
        monitor->WorkSize = main_viewport->WorkSize;
13838
34.4k
        monitor->DpiScale = main_viewport->DpiScale;
13839
34.4k
    }
13840
13841
34.4k
    if (!viewports_enabled)
13842
34.4k
    {
13843
34.4k
        g.MouseViewport = main_viewport;
13844
34.4k
        return;
13845
34.4k
    }
13846
13847
    // Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
13848
    // Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
13849
0
    ImGuiViewportP* viewport_hovered = NULL;
13850
0
    if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
13851
0
    {
13852
0
        viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
13853
0
        if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13854
0
            viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos); // Backend failed to handle _NoInputs viewport: revert to our fallback.
13855
0
    }
13856
0
    else
13857
0
    {
13858
        // If the backend doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
13859
        // A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
13860
        // B) won't take account of how the backend apply parent<>child relationship to secondary viewports, which affects their Z order.
13861
        // C) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
13862
0
        viewport_hovered = FindHoveredViewportFromPlatformWindowStack(g.IO.MousePos);
13863
0
    }
13864
0
    if (viewport_hovered != NULL)
13865
0
        g.MouseLastHoveredViewport = viewport_hovered;
13866
0
    else if (g.MouseLastHoveredViewport == NULL)
13867
0
        g.MouseLastHoveredViewport = g.Viewports[0];
13868
13869
    // Update mouse reference viewport
13870
    // (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
13871
    // (MovingViewport->Viewport will be NULL in the rare situation where the window disappared while moving, set UpdateMouseMovingWindowNewFrame() for details)
13872
0
    if (g.MovingWindow && g.MovingWindow->Viewport)
13873
0
        g.MouseViewport = g.MovingWindow->Viewport;
13874
0
    else
13875
0
        g.MouseViewport = g.MouseLastHoveredViewport;
13876
13877
    // When dragging something, always refer to the last hovered viewport.
13878
    // - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
13879
    // - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
13880
    // - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
13881
    // FIXME-VIEWPORT: This is essentially broken, when ImGuiBackendFlags_HasMouseHoveredViewport is set we want to trust when viewport_hovered==NULL and use that.
13882
0
    const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
13883
0
    if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
13884
0
        viewport_hovered = g.MouseLastHoveredViewport;
13885
0
    if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
13886
0
        if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
13887
0
            g.MouseViewport = viewport_hovered;
13888
13889
0
    IM_ASSERT(g.MouseViewport != NULL);
13890
0
}
13891
13892
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
13893
static void ImGui::UpdateViewportsEndFrame()
13894
34.4k
{
13895
34.4k
    ImGuiContext& g = *GImGui;
13896
34.4k
    g.PlatformIO.Viewports.resize(0);
13897
68.8k
    for (int i = 0; i < g.Viewports.Size; i++)
13898
34.4k
    {
13899
34.4k
        ImGuiViewportP* viewport = g.Viewports[i];
13900
34.4k
        viewport->LastPos = viewport->Pos;
13901
34.4k
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
13902
0
            if (i > 0) // Always include main viewport in the list
13903
0
                continue;
13904
34.4k
        if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
13905
0
            continue;
13906
34.4k
        if (i > 0)
13907
34.4k
            IM_ASSERT(viewport->Window != NULL);
13908
34.4k
        g.PlatformIO.Viewports.push_back(viewport);
13909
34.4k
    }
13910
34.4k
    g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
13911
34.4k
}
13912
13913
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
13914
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
13915
34.4k
{
13916
34.4k
    ImGuiContext& g = *GImGui;
13917
34.4k
    IM_ASSERT(id != 0);
13918
13919
34.4k
    flags |= ImGuiViewportFlags_IsPlatformWindow;
13920
34.4k
    if (window != NULL)
13921
0
    {
13922
0
        if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window)
13923
0
            flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
13924
0
        if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
13925
0
            flags |= ImGuiViewportFlags_NoInputs;
13926
0
        if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
13927
0
            flags |= ImGuiViewportFlags_NoFocusOnAppearing;
13928
0
    }
13929
13930
34.4k
    ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
13931
34.4k
    if (viewport)
13932
34.4k
    {
13933
        // Always update for main viewport as we are already pulling correct platform pos/size (see #4900)
13934
34.4k
        if (!viewport->PlatformRequestMove || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13935
34.4k
            viewport->Pos = pos;
13936
34.4k
        if (!viewport->PlatformRequestResize || viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID)
13937
34.4k
            viewport->Size = size;
13938
34.4k
        viewport->Flags = flags | (viewport->Flags & ImGuiViewportFlags_Minimized); // Preserve existing flags
13939
34.4k
    }
13940
0
    else
13941
0
    {
13942
        // New viewport
13943
0
        viewport = IM_NEW(ImGuiViewportP)();
13944
0
        viewport->ID = id;
13945
0
        viewport->Idx = g.Viewports.Size;
13946
0
        viewport->Pos = viewport->LastPos = pos;
13947
0
        viewport->Size = size;
13948
0
        viewport->Flags = flags;
13949
0
        UpdateViewportPlatformMonitor(viewport);
13950
0
        g.Viewports.push_back(viewport);
13951
0
        IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Add Viewport %08X '%s'\n", id, window ? window->Name : "<NULL>");
13952
13953
        // We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
13954
        // We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
13955
0
        g.DrawListSharedData.ClipRectFullscreen.x = ImMin(g.DrawListSharedData.ClipRectFullscreen.x, viewport->Pos.x);
13956
0
        g.DrawListSharedData.ClipRectFullscreen.y = ImMin(g.DrawListSharedData.ClipRectFullscreen.y, viewport->Pos.y);
13957
0
        g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
13958
0
        g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
13959
13960
        // Store initial DpiScale before the OS platform window creation, based on expected monitor data.
13961
        // This is so we can select an appropriate font size on the first frame of our window lifetime
13962
0
        if (viewport->PlatformMonitor != -1)
13963
0
            viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
13964
0
    }
13965
13966
34.4k
    viewport->Window = window;
13967
34.4k
    viewport->LastFrameActive = g.FrameCount;
13968
34.4k
    viewport->UpdateWorkRect();
13969
34.4k
    IM_ASSERT(window == NULL || viewport->ID == window->ID);
13970
13971
34.4k
    if (window != NULL)
13972
0
        window->ViewportOwned = true;
13973
13974
34.4k
    return viewport;
13975
34.4k
}
13976
13977
static void ImGui::DestroyViewport(ImGuiViewportP* viewport)
13978
0
{
13979
    // Clear references to this viewport in windows (window->ViewportId becomes the master data)
13980
0
    ImGuiContext& g = *GImGui;
13981
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
13982
0
    {
13983
0
        ImGuiWindow* window = g.Windows[window_n];
13984
0
        if (window->Viewport != viewport)
13985
0
            continue;
13986
0
        window->Viewport = NULL;
13987
0
        window->ViewportOwned = false;
13988
0
    }
13989
0
    if (viewport == g.MouseLastHoveredViewport)
13990
0
        g.MouseLastHoveredViewport = NULL;
13991
13992
    // Destroy
13993
0
    IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Delete Viewport %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
13994
0
    DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
13995
0
    IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
13996
0
    IM_ASSERT(g.Viewports[viewport->Idx] == viewport);
13997
0
    g.Viewports.erase(g.Viewports.Data + viewport->Idx);
13998
0
    IM_DELETE(viewport);
13999
0
}
14000
14001
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
14002
static void ImGui::WindowSelectViewport(ImGuiWindow* window)
14003
71.9k
{
14004
71.9k
    ImGuiContext& g = *GImGui;
14005
71.9k
    ImGuiWindowFlags flags = window->Flags;
14006
71.9k
    window->ViewportAllowPlatformMonitorExtend = -1;
14007
14008
    // Restore main viewport if multi-viewport is not supported by the backend
14009
71.9k
    ImGuiViewportP* main_viewport = (ImGuiViewportP*)(void*)GetMainViewport();
14010
71.9k
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14011
71.9k
    {
14012
71.9k
        SetWindowViewport(window, main_viewport);
14013
71.9k
        return;
14014
71.9k
    }
14015
0
    window->ViewportOwned = false;
14016
14017
    // Appearing popups reset their viewport so they can inherit again
14018
0
    if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
14019
0
    {
14020
0
        window->Viewport = NULL;
14021
0
        window->ViewportId = 0;
14022
0
    }
14023
14024
0
    if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport) == 0)
14025
0
    {
14026
        // By default inherit from parent window
14027
0
        if (window->Viewport == NULL && window->ParentWindow && (!window->ParentWindow->IsFallbackWindow || window->ParentWindow->WasActive))
14028
0
            window->Viewport = window->ParentWindow->Viewport;
14029
14030
        // Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
14031
0
        if (window->Viewport == NULL && window->ViewportId != 0)
14032
0
        {
14033
0
            window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
14034
0
            if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
14035
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
14036
0
        }
14037
0
    }
14038
14039
0
    bool lock_viewport = false;
14040
0
    if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasViewport)
14041
0
    {
14042
        // Code explicitly request a viewport
14043
0
        window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
14044
0
        window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
14045
0
        lock_viewport = true;
14046
0
    }
14047
0
    else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
14048
0
    {
14049
        // Always inherit viewport from parent window
14050
0
        if (window->DockNode && window->DockNode->HostWindow)
14051
0
            IM_ASSERT(window->DockNode->HostWindow->Viewport == window->ParentWindow->Viewport);
14052
0
        window->Viewport = window->ParentWindow->Viewport;
14053
0
    }
14054
0
    else if (window->DockNode && window->DockNode->HostWindow)
14055
0
    {
14056
        // This covers the "always inherit viewport from parent window" case for when a window reattach to a node that was just created mid-frame
14057
0
        window->Viewport = window->DockNode->HostWindow->Viewport;
14058
0
    }
14059
0
    else if (flags & ImGuiWindowFlags_Tooltip)
14060
0
    {
14061
0
        window->Viewport = g.MouseViewport;
14062
0
    }
14063
0
    else if (GetWindowAlwaysWantOwnViewport(window))
14064
0
    {
14065
0
        window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14066
0
    }
14067
0
    else if (g.MovingWindow && g.MovingWindow->RootWindowDockTree == window && IsMousePosValid())
14068
0
    {
14069
0
        if (window->Viewport != NULL && window->Viewport->Window == window)
14070
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14071
0
    }
14072
0
    else
14073
0
    {
14074
        // Merge into host viewport?
14075
        // We cannot test window->ViewportOwned as it set lower in the function.
14076
        // Testing (g.ActiveId == 0 || g.ActiveIdAllowOverlap) to avoid merging during a short-term widget interaction. Main intent was to avoid during resize (see #4212)
14077
0
        bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && (g.ActiveId == 0 || g.ActiveIdAllowOverlap));
14078
0
        if (try_to_merge_into_host_viewport)
14079
0
            UpdateTryMergeWindowIntoHostViewports(window);
14080
0
    }
14081
14082
    // Fallback: merge in default viewport if z-order matches, otherwise create a new viewport
14083
0
    if (window->Viewport == NULL)
14084
0
        if (!UpdateTryMergeWindowIntoHostViewport(window, main_viewport))
14085
0
            window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
14086
14087
    // Mark window as allowed to protrude outside of its viewport and into the current monitor
14088
0
    if (!lock_viewport)
14089
0
    {
14090
0
        if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
14091
0
        {
14092
            // We need to take account of the possibility that mouse may become invalid.
14093
            // Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
14094
0
            ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
14095
0
            bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
14096
0
            bool mouse_valid = IsMousePosValid(&mouse_ref);
14097
0
            if ((window->Appearing || (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_ChildMenu))) && (!use_mouse_ref || mouse_valid))
14098
0
                window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
14099
0
            else
14100
0
                window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14101
0
        }
14102
0
        else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL)
14103
0
        {
14104
            // When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
14105
0
            const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
14106
0
            if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
14107
0
            {
14108
                // Steal/transfer ownership
14109
0
                IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Window '%s' steal Viewport %08X from Window '%s'\n", window->Name, window->Viewport->ID, window->Viewport->Window->Name);
14110
0
                window->Viewport->Window = window;
14111
0
                window->Viewport->ID = window->ID;
14112
0
                window->Viewport->LastNameHash = 0;
14113
0
            }
14114
0
            else if (!UpdateTryMergeWindowIntoHostViewports(window)) // Merge?
14115
0
            {
14116
                // New viewport
14117
0
                window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
14118
0
            }
14119
0
        }
14120
0
        else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
14121
0
        {
14122
            // Regular (non-child, non-popup) windows by default are also allowed to protrude
14123
            // Child windows are kept contained within their parent.
14124
0
            window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
14125
0
        }
14126
0
    }
14127
14128
    // Update flags
14129
0
    window->ViewportOwned = (window == window->Viewport->Window);
14130
0
    window->ViewportId = window->Viewport->ID;
14131
14132
    // If the OS window has a title bar, hide our imgui title bar
14133
    //if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
14134
    //    window->Flags |= ImGuiWindowFlags_NoTitleBar;
14135
0
}
14136
14137
void ImGui::WindowSyncOwnedViewport(ImGuiWindow* window, ImGuiWindow* parent_window_in_stack)
14138
0
{
14139
0
    ImGuiContext& g = *GImGui;
14140
14141
0
    bool viewport_rect_changed = false;
14142
14143
    // Synchronize window --> viewport in most situations
14144
    // Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
14145
0
    if (window->Viewport->PlatformRequestMove)
14146
0
    {
14147
0
        window->Pos = window->Viewport->Pos;
14148
0
        MarkIniSettingsDirty(window);
14149
0
    }
14150
0
    else if (memcmp(&window->Viewport->Pos, &window->Pos, sizeof(window->Pos)) != 0)
14151
0
    {
14152
0
        viewport_rect_changed = true;
14153
0
        window->Viewport->Pos = window->Pos;
14154
0
    }
14155
14156
0
    if (window->Viewport->PlatformRequestResize)
14157
0
    {
14158
0
        window->Size = window->SizeFull = window->Viewport->Size;
14159
0
        MarkIniSettingsDirty(window);
14160
0
    }
14161
0
    else if (memcmp(&window->Viewport->Size, &window->Size, sizeof(window->Size)) != 0)
14162
0
    {
14163
0
        viewport_rect_changed = true;
14164
0
        window->Viewport->Size = window->Size;
14165
0
    }
14166
0
    window->Viewport->UpdateWorkRect();
14167
14168
    // The viewport may have changed monitor since the global update in UpdateViewportsNewFrame()
14169
    // Either a SetNextWindowPos() call in the current frame or a SetWindowPos() call in the previous frame may have this effect.
14170
0
    if (viewport_rect_changed)
14171
0
        UpdateViewportPlatformMonitor(window->Viewport);
14172
14173
    // Update common viewport flags
14174
0
    const ImGuiViewportFlags viewport_flags_to_clear = ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration | ImGuiViewportFlags_NoRendererClear;
14175
0
    ImGuiViewportFlags viewport_flags = window->Viewport->Flags & ~viewport_flags_to_clear;
14176
0
    ImGuiWindowFlags window_flags = window->Flags;
14177
0
    const bool is_modal = (window_flags & ImGuiWindowFlags_Modal) != 0;
14178
0
    const bool is_short_lived_floating_window = (window_flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0;
14179
0
    if (window_flags & ImGuiWindowFlags_Tooltip)
14180
0
        viewport_flags |= ImGuiViewportFlags_TopMost;
14181
0
    if ((g.IO.ConfigViewportsNoTaskBarIcon || is_short_lived_floating_window) && !is_modal)
14182
0
        viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
14183
0
    if (g.IO.ConfigViewportsNoDecoration || is_short_lived_floating_window)
14184
0
        viewport_flags |= ImGuiViewportFlags_NoDecoration;
14185
14186
    // Not correct to set modal as topmost because:
14187
    // - Because other popups can be stacked above a modal (e.g. combo box in a modal)
14188
    // - ImGuiViewportFlags_TopMost is currently handled different in backends: in Win32 it is "appear top most" whereas in GLFW and SDL it is "stay topmost"
14189
    //if (flags & ImGuiWindowFlags_Modal)
14190
    //    viewport_flags |= ImGuiViewportFlags_TopMost;
14191
14192
    // For popups and menus that may be protruding out of their parent viewport, we enable _NoFocusOnClick so that clicking on them
14193
    // won't steal the OS focus away from their parent window (which may be reflected in OS the title bar decoration).
14194
    // Setting _NoFocusOnClick would technically prevent us from bringing back to front in case they are being covered by an OS window from a different app,
14195
    // but it shouldn't be much of a problem considering those are already popups that are closed when clicking elsewhere.
14196
0
    if (is_short_lived_floating_window && !is_modal)
14197
0
        viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
14198
14199
    // We can overwrite viewport flags using ImGuiWindowClass (advanced users)
14200
0
    if (window->WindowClass.ViewportFlagsOverrideSet)
14201
0
        viewport_flags |= window->WindowClass.ViewportFlagsOverrideSet;
14202
0
    if (window->WindowClass.ViewportFlagsOverrideClear)
14203
0
        viewport_flags &= ~window->WindowClass.ViewportFlagsOverrideClear;
14204
14205
    // We can also tell the backend that clearing the platform window won't be necessary,
14206
    // as our window background is filling the viewport and we have disabled BgAlpha.
14207
    // FIXME: Work on support for per-viewport transparency (#2766)
14208
0
    if (!(window_flags & ImGuiWindowFlags_NoBackground))
14209
0
        viewport_flags |= ImGuiViewportFlags_NoRendererClear;
14210
14211
0
    window->Viewport->Flags = viewport_flags;
14212
14213
    // Update parent viewport ID
14214
    // (the !IsFallbackWindow test mimic the one done in WindowSelectViewport())
14215
0
    if (window->WindowClass.ParentViewportId != (ImGuiID)-1)
14216
0
        window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
14217
0
    else if ((window_flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && parent_window_in_stack && (!parent_window_in_stack->IsFallbackWindow || parent_window_in_stack->WasActive))
14218
0
        window->Viewport->ParentViewportId = parent_window_in_stack->Viewport->ID;
14219
0
    else
14220
0
        window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoDefaultParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
14221
0
}
14222
14223
// Called by user at the end of the main loop, after EndFrame()
14224
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
14225
void ImGui::UpdatePlatformWindows()
14226
0
{
14227
0
    ImGuiContext& g = *GImGui;
14228
0
    IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
14229
0
    IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
14230
0
    g.FrameCountPlatformEnded = g.FrameCount;
14231
0
    if (!(g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable))
14232
0
        return;
14233
14234
    // Create/resize/destroy platform windows to match each active viewport.
14235
    // Skip the main viewport (index 0), which is always fully handled by the application!
14236
0
    for (int i = 1; i < g.Viewports.Size; i++)
14237
0
    {
14238
0
        ImGuiViewportP* viewport = g.Viewports[i];
14239
14240
        // Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window
14241
        // (the implicit/fallback Debug##Default window will be registering its viewport then be disabled, causing a dummy DestroyPlatformWindow to be made each frame)
14242
0
        bool destroy_platform_window = false;
14243
0
        destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
14244
0
        destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
14245
0
        if (destroy_platform_window)
14246
0
        {
14247
0
            DestroyPlatformWindow(viewport);
14248
0
            continue;
14249
0
        }
14250
14251
        // New windows that appears directly in a new viewport won't always have a size on their first frame
14252
0
        if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
14253
0
            continue;
14254
14255
        // Create window
14256
0
        const bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
14257
0
        if (is_new_platform_window)
14258
0
        {
14259
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Create Platform Window %08X '%s'\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
14260
0
            g.PlatformIO.Platform_CreateWindow(viewport);
14261
0
            if (g.PlatformIO.Renderer_CreateWindow != NULL)
14262
0
                g.PlatformIO.Renderer_CreateWindow(viewport);
14263
0
            viewport->LastNameHash = 0;
14264
0
            viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
14265
0
            viewport->LastRendererSize = viewport->Size;                                       // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
14266
0
            viewport->PlatformWindowCreated = true;
14267
0
        }
14268
14269
        // Apply Position and Size (from ImGui to Platform/Renderer backends)
14270
0
        if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
14271
0
            g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
14272
0
        if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
14273
0
            g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
14274
0
        if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
14275
0
            g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
14276
0
        viewport->LastPlatformPos = viewport->Pos;
14277
0
        viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
14278
14279
        // Update title bar (if it changed)
14280
0
        if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
14281
0
        {
14282
0
            const char* title_begin = window_for_title->Name;
14283
0
            char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
14284
0
            const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
14285
0
            if (viewport->LastNameHash != title_hash)
14286
0
            {
14287
0
                char title_end_backup_c = *title_end;
14288
0
                *title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
14289
0
                g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
14290
0
                *title_end = title_end_backup_c;
14291
0
                viewport->LastNameHash = title_hash;
14292
0
            }
14293
0
        }
14294
14295
        // Update alpha (if it changed)
14296
0
        if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
14297
0
            g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
14298
0
        viewport->LastAlpha = viewport->Alpha;
14299
14300
        // Optional, general purpose call to allow the backend to perform general book-keeping even if things haven't changed.
14301
0
        if (g.PlatformIO.Platform_UpdateWindow)
14302
0
            g.PlatformIO.Platform_UpdateWindow(viewport);
14303
14304
0
        if (is_new_platform_window)
14305
0
        {
14306
            // On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
14307
0
            if (g.FrameCount < 3)
14308
0
                viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
14309
14310
            // Show window
14311
0
            g.PlatformIO.Platform_ShowWindow(viewport);
14312
14313
            // Even without focus, we assume the window becomes front-most.
14314
            // This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
14315
0
            if (viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14316
0
                viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14317
0
            }
14318
14319
        // Clear request flags
14320
0
        viewport->ClearRequestFlags();
14321
0
    }
14322
14323
    // Update our implicit z-order knowledge of platform windows, which is used when the backend cannot provide io.MouseHoveredViewport.
14324
    // When setting Platform_GetWindowFocus, it is expected that the platform backend can handle calls without crashing if it doesn't have data stored.
14325
    // FIXME-VIEWPORT: We should use this information to also set dear imgui-side focus, allowing us to handle os-level alt+tab.
14326
0
    if (g.PlatformIO.Platform_GetWindowFocus != NULL)
14327
0
    {
14328
0
        ImGuiViewportP* focused_viewport = NULL;
14329
0
        for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
14330
0
        {
14331
0
            ImGuiViewportP* viewport = g.Viewports[n];
14332
0
            if (viewport->PlatformWindowCreated)
14333
0
                if (g.PlatformIO.Platform_GetWindowFocus(viewport))
14334
0
                    focused_viewport = viewport;
14335
0
        }
14336
14337
        // Store a tag so we can infer z-order easily from all our windows
14338
        // We compare PlatformLastFocusedViewportId so newly created viewports with _NoFocusOnAppearing flag
14339
        // will keep the front most stamp instead of losing it back to their parent viewport.
14340
0
        if (focused_viewport && g.PlatformLastFocusedViewportId != focused_viewport->ID)
14341
0
        {
14342
0
            if (focused_viewport->LastFrontMostStampCount != g.ViewportFrontMostStampCount)
14343
0
                focused_viewport->LastFrontMostStampCount = ++g.ViewportFrontMostStampCount;
14344
0
            g.PlatformLastFocusedViewportId = focused_viewport->ID;
14345
0
        }
14346
0
    }
14347
0
}
14348
14349
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
14350
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
14351
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
14352
//
14353
//    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14354
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14355
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14356
//            MyRenderFunction(platform_io.Viewports[i], my_args);
14357
//    for (int i = 1; i < platform_io.Viewports.Size; i++)
14358
//        if ((platform_io.Viewports[i]->Flags & ImGuiViewportFlags_Minimized) == 0)
14359
//            MySwapBufferFunction(platform_io.Viewports[i], my_args);
14360
//
14361
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
14362
0
{
14363
    // Skip the main viewport (index 0), which is always fully handled by the application!
14364
0
    ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
14365
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14366
0
    {
14367
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14368
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14369
0
            continue;
14370
0
        if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
14371
0
        if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
14372
0
    }
14373
0
    for (int i = 1; i < platform_io.Viewports.Size; i++)
14374
0
    {
14375
0
        ImGuiViewport* viewport = platform_io.Viewports[i];
14376
0
        if (viewport->Flags & ImGuiViewportFlags_Minimized)
14377
0
            continue;
14378
0
        if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
14379
0
        if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
14380
0
    }
14381
0
}
14382
14383
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
14384
0
{
14385
0
    ImGuiContext& g = *GImGui;
14386
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
14387
0
    {
14388
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14389
0
        if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
14390
0
            return monitor_n;
14391
0
    }
14392
0
    return -1;
14393
0
}
14394
14395
// Search for the monitor with the largest intersection area with the given rectangle
14396
// We generally try to avoid searching loops but the monitor count should be very small here
14397
// FIXME-OPT: We could test the last monitor used for that viewport first, and early
14398
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
14399
34.4k
{
14400
34.4k
    ImGuiContext& g = *GImGui;
14401
14402
34.4k
    const int monitor_count = g.PlatformIO.Monitors.Size;
14403
34.4k
    if (monitor_count <= 1)
14404
34.4k
        return monitor_count - 1;
14405
14406
    // Use a minimum threshold of 1.0f so a zero-sized rect won't false positive, and will still find the correct monitor given its position.
14407
    // This is necessary for tooltips which always resize down to zero at first.
14408
0
    const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
14409
0
    int best_monitor_n = -1;
14410
0
    float best_monitor_surface = 0.001f;
14411
14412
0
    for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
14413
0
    {
14414
0
        const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
14415
0
        const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
14416
0
        if (monitor_rect.Contains(rect))
14417
0
            return monitor_n;
14418
0
        ImRect overlapping_rect = rect;
14419
0
        overlapping_rect.ClipWithFull(monitor_rect);
14420
0
        float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
14421
0
        if (overlapping_surface < best_monitor_surface)
14422
0
            continue;
14423
0
        best_monitor_surface = overlapping_surface;
14424
0
        best_monitor_n = monitor_n;
14425
0
    }
14426
0
    return best_monitor_n;
14427
0
}
14428
14429
// Update monitor from viewport rectangle (we'll use this info to clamp windows and save windows lost in a removed monitor)
14430
static void ImGui::UpdateViewportPlatformMonitor(ImGuiViewportP* viewport)
14431
34.4k
{
14432
34.4k
    viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetMainRect());
14433
34.4k
}
14434
14435
// Return value is always != NULL, but don't hold on it across frames.
14436
const ImGuiPlatformMonitor* ImGui::GetViewportPlatformMonitor(ImGuiViewport* viewport_p)
14437
0
{
14438
0
    ImGuiContext& g = *GImGui;
14439
0
    ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)viewport_p;
14440
0
    int monitor_idx = viewport->PlatformMonitor;
14441
0
    if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
14442
0
        return &g.PlatformIO.Monitors[monitor_idx];
14443
0
    return &g.FallbackMonitor;
14444
0
}
14445
14446
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
14447
0
{
14448
0
    ImGuiContext& g = *GImGui;
14449
0
    if (viewport->PlatformWindowCreated)
14450
0
    {
14451
0
        if (g.PlatformIO.Renderer_DestroyWindow)
14452
0
            g.PlatformIO.Renderer_DestroyWindow(viewport);
14453
0
        if (g.PlatformIO.Platform_DestroyWindow)
14454
0
            g.PlatformIO.Platform_DestroyWindow(viewport);
14455
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL);
14456
14457
        // Don't clear PlatformWindowCreated for the main viewport, as we initially set that up to true in Initialize()
14458
        // The righter way may be to leave it to the backend to set this flag all-together, and made the flag public.
14459
0
        if (viewport->ID != IMGUI_VIEWPORT_DEFAULT_ID)
14460
0
            viewport->PlatformWindowCreated = false;
14461
0
    }
14462
0
    else
14463
0
    {
14464
0
        IM_ASSERT(viewport->RendererUserData == NULL && viewport->PlatformUserData == NULL && viewport->PlatformHandle == NULL);
14465
0
    }
14466
0
    viewport->RendererUserData = viewport->PlatformUserData = viewport->PlatformHandle = NULL;
14467
0
    viewport->ClearRequestFlags();
14468
0
}
14469
14470
void ImGui::DestroyPlatformWindows()
14471
0
{
14472
    // We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the backend
14473
    // to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
14474
    // It is convenient for the platform backend code to store something in the main viewport, in order for e.g. the mouse handling
14475
    // code to operator a consistent manner.
14476
    // It is expected that the backend can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
14477
    // crashing if it doesn't have data stored.
14478
0
    ImGuiContext& g = *GImGui;
14479
0
    for (int i = 0; i < g.Viewports.Size; i++)
14480
0
        DestroyPlatformWindow(g.Viewports[i]);
14481
0
}
14482
14483
14484
//-----------------------------------------------------------------------------
14485
// [SECTION] DOCKING
14486
//-----------------------------------------------------------------------------
14487
// Docking: Internal Types
14488
// Docking: Forward Declarations
14489
// Docking: ImGuiDockContext
14490
// Docking: ImGuiDockContext Docking/Undocking functions
14491
// Docking: ImGuiDockNode
14492
// Docking: ImGuiDockNode Tree manipulation functions
14493
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
14494
// Docking: Builder Functions
14495
// Docking: Begin/End Support Functions (called from Begin/End)
14496
// Docking: Settings
14497
//-----------------------------------------------------------------------------
14498
14499
//-----------------------------------------------------------------------------
14500
// Typical Docking call flow: (root level is generally public API):
14501
//-----------------------------------------------------------------------------
14502
// - NewFrame()                               new dear imgui frame
14503
//    | DockContextNewFrameUpdateUndocking()  - process queued undocking requests
14504
//    | - DockContextProcessUndockWindow()    - process one window undocking request
14505
//    | - DockContextProcessUndockNode()      - process one whole node undocking request
14506
//    | DockContextNewFrameUpdateUndocking()  - process queue docking requests, create floating dock nodes
14507
//    | - update g.HoveredDockNode            - [debug] update node hovered by mouse
14508
//    | - DockContextProcessDock()            - process one docking request
14509
//    | - DockNodeUpdate()
14510
//    |   - DockNodeUpdateForRootNode()
14511
//    |     - DockNodeUpdateFlagsAndCollapse()
14512
//    |     - DockNodeFindInfo()
14513
//    |   - destroy unused node or tab bar
14514
//    |   - create dock node host window
14515
//    |      - Begin() etc.
14516
//    |   - DockNodeStartMouseMovingWindow()
14517
//    |   - DockNodeTreeUpdatePosSize()
14518
//    |   - DockNodeTreeUpdateSplitter()
14519
//    |   - draw node background
14520
//    |   - DockNodeUpdateTabBar()            - create/update tab bar for a docking node
14521
//    |     - DockNodeAddTabBar()
14522
//    |     - DockNodeUpdateWindowMenu()
14523
//    |     - DockNodeCalcTabBarLayout()
14524
//    |     - BeginTabBarEx()
14525
//    |     - TabItemEx() calls
14526
//    |     - EndTabBar()
14527
//    |   - BeginDockableDragDropTarget()
14528
//    |      - DockNodeUpdate()               - recurse into child nodes...
14529
//-----------------------------------------------------------------------------
14530
// - DockSpace()                              user submit a dockspace into a window
14531
//    | Begin(Child)                          - create a child window
14532
//    | DockNodeUpdate()                      - call main dock node update function
14533
//    | End(Child)
14534
//    | ItemSize()
14535
//-----------------------------------------------------------------------------
14536
// - Begin()
14537
//    | BeginDocked()
14538
//    | BeginDockableDragDropSource()
14539
//    | BeginDockableDragDropTarget()
14540
//    | - DockNodePreviewDockRender()
14541
//-----------------------------------------------------------------------------
14542
// - EndFrame()
14543
//    | DockContextEndFrame()
14544
//-----------------------------------------------------------------------------
14545
14546
//-----------------------------------------------------------------------------
14547
// Docking: Internal Types
14548
//-----------------------------------------------------------------------------
14549
// - ImGuiDockRequestType
14550
// - ImGuiDockRequest
14551
// - ImGuiDockPreviewData
14552
// - ImGuiDockNodeSettings
14553
// - ImGuiDockContext
14554
//-----------------------------------------------------------------------------
14555
14556
enum ImGuiDockRequestType
14557
{
14558
    ImGuiDockRequestType_None = 0,
14559
    ImGuiDockRequestType_Dock,
14560
    ImGuiDockRequestType_Undock,
14561
    ImGuiDockRequestType_Split                  // Split is the same as Dock but without a DockPayload
14562
};
14563
14564
struct ImGuiDockRequest
14565
{
14566
    ImGuiDockRequestType    Type;
14567
    ImGuiWindow*            DockTargetWindow;   // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
14568
    ImGuiDockNode*          DockTargetNode;     // Destination/Target Node to dock into
14569
    ImGuiWindow*            DockPayload;        // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
14570
    ImGuiDir                DockSplitDir;
14571
    float                   DockSplitRatio;
14572
    bool                    DockSplitOuter;
14573
    ImGuiWindow*            UndockTargetWindow;
14574
    ImGuiDockNode*          UndockTargetNode;
14575
14576
    ImGuiDockRequest()
14577
0
    {
14578
0
        Type = ImGuiDockRequestType_None;
14579
0
        DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
14580
0
        DockTargetNode = UndockTargetNode = NULL;
14581
0
        DockSplitDir = ImGuiDir_None;
14582
0
        DockSplitRatio = 0.5f;
14583
0
        DockSplitOuter = false;
14584
0
    }
14585
};
14586
14587
struct ImGuiDockPreviewData
14588
{
14589
    ImGuiDockNode   FutureNode;
14590
    bool            IsDropAllowed;
14591
    bool            IsCenterAvailable;
14592
    bool            IsSidesAvailable;           // Hold your breath, grammar freaks..
14593
    bool            IsSplitDirExplicit;         // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
14594
    ImGuiDockNode*  SplitNode;
14595
    ImGuiDir        SplitDir;
14596
    float           SplitRatio;
14597
    ImRect          DropRectsDraw[ImGuiDir_COUNT + 1];  // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
14598
14599
0
    ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; for (int n = 0; n < IM_ARRAYSIZE(DropRectsDraw); n++) DropRectsDraw[n] = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX); }
14600
};
14601
14602
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
14603
struct ImGuiDockNodeSettings
14604
{
14605
    ImGuiID             ID;
14606
    ImGuiID             ParentNodeId;
14607
    ImGuiID             ParentWindowId;
14608
    ImGuiID             SelectedTabId;
14609
    signed char         SplitAxis;
14610
    char                Depth;
14611
    ImGuiDockNodeFlags  Flags;                  // NB: We save individual flags one by one in ascii format (ImGuiDockNodeFlags_SavedFlagsMask_)
14612
    ImVec2ih            Pos;
14613
    ImVec2ih            Size;
14614
    ImVec2ih            SizeRef;
14615
0
    ImGuiDockNodeSettings() { memset(this, 0, sizeof(*this)); SplitAxis = ImGuiAxis_None; }
14616
};
14617
14618
//-----------------------------------------------------------------------------
14619
// Docking: Forward Declarations
14620
//-----------------------------------------------------------------------------
14621
14622
namespace ImGui
14623
{
14624
    // ImGuiDockContext
14625
    static ImGuiDockNode*   DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
14626
    static void             DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
14627
    static void             DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
14628
    static void             DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
14629
    static void             DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
14630
    static ImGuiDockNode*   DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window);
14631
    static void             DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
14632
    static void             DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id);                            // Use root_id==0 to add all
14633
14634
    // ImGuiDockNode
14635
    static void             DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
14636
    static void             DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14637
    static void             DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
14638
    static ImGuiWindow*     DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id);
14639
    static void             DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
14640
    static void             DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
14641
    static void             DockNodeHideHostWindow(ImGuiDockNode* node);
14642
    static void             DockNodeUpdate(ImGuiDockNode* node);
14643
    static void             DockNodeUpdateForRootNode(ImGuiDockNode* node);
14644
    static void             DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node);
14645
    static void             DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node);
14646
    static void             DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
14647
    static void             DockNodeAddTabBar(ImGuiDockNode* node);
14648
    static void             DockNodeRemoveTabBar(ImGuiDockNode* node);
14649
    static ImGuiID          DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
14650
    static void             DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
14651
    static void             DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
14652
    static bool             DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
14653
    static void             DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
14654
    static void             DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
14655
    static void             DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos);
14656
    static void             DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
14657
    static bool             DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking, ImVec2* test_mouse_pos);
14658
0
    static const char*      DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
14659
    static int              DockNodeGetTabOrder(ImGuiWindow* window);
14660
14661
    // ImGuiDockNode tree manipulations
14662
    static void             DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
14663
    static void             DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
14664
    static void             DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node = NULL);
14665
    static void             DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
14666
    static ImGuiDockNode*   DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos);
14667
    static ImGuiDockNode*   DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
14668
14669
    // Settings
14670
    static void             DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
14671
    static void             DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
14672
    static ImGuiDockNodeSettings*   DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
14673
    static void             DockSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
14674
    static void             DockSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
14675
    static void*            DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
14676
    static void             DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
14677
    static void             DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
14678
}
14679
14680
//-----------------------------------------------------------------------------
14681
// Docking: ImGuiDockContext
14682
//-----------------------------------------------------------------------------
14683
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
14684
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
14685
// At boot time only, we run a simple GC to remove nodes that have no references.
14686
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
14687
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
14688
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
14689
//-----------------------------------------------------------------------------
14690
// - DockContextInitialize()
14691
// - DockContextShutdown()
14692
// - DockContextClearNodes()
14693
// - DockContextRebuildNodes()
14694
// - DockContextNewFrameUpdateUndocking()
14695
// - DockContextNewFrameUpdateDocking()
14696
// - DockContextEndFrame()
14697
// - DockContextFindNodeByID()
14698
// - DockContextBindNodeToWindow()
14699
// - DockContextGenNodeID()
14700
// - DockContextAddNode()
14701
// - DockContextRemoveNode()
14702
// - ImGuiDockContextPruneNodeData
14703
// - DockContextPruneUnusedSettingsNodes()
14704
// - DockContextBuildNodesFromSettings()
14705
// - DockContextBuildAddWindowsToNodes()
14706
//-----------------------------------------------------------------------------
14707
14708
void ImGui::DockContextInitialize(ImGuiContext* ctx)
14709
1
{
14710
1
    ImGuiContext& g = *ctx;
14711
14712
    // Add .ini handle for persistent docking data
14713
1
    ImGuiSettingsHandler ini_handler;
14714
1
    ini_handler.TypeName = "Docking";
14715
1
    ini_handler.TypeHash = ImHashStr("Docking");
14716
1
    ini_handler.ClearAllFn = DockSettingsHandler_ClearAll;
14717
1
    ini_handler.ReadInitFn = DockSettingsHandler_ClearAll; // Also clear on read
14718
1
    ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
14719
1
    ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
14720
1
    ini_handler.ApplyAllFn = DockSettingsHandler_ApplyAll;
14721
1
    ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
14722
1
    g.SettingsHandlers.push_back(ini_handler);
14723
1
}
14724
14725
void ImGui::DockContextShutdown(ImGuiContext* ctx)
14726
0
{
14727
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14728
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14729
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14730
0
            IM_DELETE(node);
14731
0
}
14732
14733
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_settings_refs)
14734
0
{
14735
0
    IM_UNUSED(ctx);
14736
0
    IM_ASSERT(ctx == GImGui);
14737
0
    DockBuilderRemoveNodeDockedWindows(root_id, clear_settings_refs);
14738
0
    DockBuilderRemoveNodeChildNodes(root_id);
14739
0
}
14740
14741
// [DEBUG] This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
14742
// (Different from DockSettingsHandler_ClearAll() + DockSettingsHandler_ApplyAll() because this reuses current settings!)
14743
void ImGui::DockContextRebuildNodes(ImGuiContext* ctx)
14744
0
{
14745
0
    ImGuiContext& g = *ctx;
14746
0
    ImGuiDockContext* dc = &ctx->DockContext;
14747
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRebuildNodes\n");
14748
0
    SaveIniSettingsToMemory();
14749
0
    ImGuiID root_id = 0; // Rebuild all
14750
0
    DockContextClearNodes(ctx, root_id, false);
14751
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
14752
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
14753
0
}
14754
14755
// Docking context update function, called by NewFrame()
14756
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
14757
34.4k
{
14758
34.4k
    ImGuiContext& g = *ctx;
14759
34.4k
    ImGuiDockContext* dc = &ctx->DockContext;
14760
34.4k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14761
0
    {
14762
0
        if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
14763
0
            DockContextClearNodes(ctx, 0, true);
14764
0
        return;
14765
0
    }
14766
14767
    // Setting NoSplit at runtime merges all nodes
14768
34.4k
    if (g.IO.ConfigDockingNoSplit)
14769
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
14770
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14771
0
                if (node->IsRootNode() && node->IsSplitNode())
14772
0
                {
14773
0
                    DockBuilderRemoveNodeChildNodes(node->ID);
14774
                    //dc->WantFullRebuild = true;
14775
0
                }
14776
14777
    // Process full rebuild
14778
#if 0
14779
    if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
14780
        dc->WantFullRebuild = true;
14781
#endif
14782
34.4k
    if (dc->WantFullRebuild)
14783
0
    {
14784
0
        DockContextRebuildNodes(ctx);
14785
0
        dc->WantFullRebuild = false;
14786
0
    }
14787
14788
    // Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
14789
34.4k
    for (int n = 0; n < dc->Requests.Size; n++)
14790
0
    {
14791
0
        ImGuiDockRequest* req = &dc->Requests[n];
14792
0
        if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
14793
0
            DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
14794
0
        else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
14795
0
            DockContextProcessUndockNode(ctx, req->UndockTargetNode);
14796
0
    }
14797
34.4k
}
14798
14799
// Docking context update function, called by NewFrame()
14800
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
14801
34.4k
{
14802
34.4k
    ImGuiContext& g = *ctx;
14803
34.4k
    ImGuiDockContext* dc  = &ctx->DockContext;
14804
34.4k
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
14805
0
        return;
14806
14807
    // [DEBUG] Store hovered dock node.
14808
    // We could in theory use DockNodeTreeFindVisibleNodeByPos() on the root host dock node, but using ->DockNode is a good shortcut.
14809
    // Note this is mostly a debug thing and isn't actually used for docking target, because docking involve more detailed filtering.
14810
34.4k
    g.DebugHoveredDockNode = NULL;
14811
34.4k
    if (ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow)
14812
1.16k
    {
14813
1.16k
        if (hovered_window->DockNodeAsHost)
14814
0
            g.DebugHoveredDockNode = DockNodeTreeFindVisibleNodeByPos(hovered_window->DockNodeAsHost, g.IO.MousePos);
14815
1.16k
        else if (hovered_window->RootWindow->DockNode)
14816
0
            g.DebugHoveredDockNode = hovered_window->RootWindow->DockNode;
14817
1.16k
    }
14818
14819
    // Process Docking requests
14820
34.4k
    for (int n = 0; n < dc->Requests.Size; n++)
14821
0
        if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
14822
0
            DockContextProcessDock(ctx, &dc->Requests[n]);
14823
34.4k
    dc->Requests.resize(0);
14824
14825
    // Create windows for each automatic docking nodes
14826
    // We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
14827
34.4k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14828
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14829
0
            if (node->IsFloatingNode())
14830
0
                DockNodeUpdate(node);
14831
34.4k
}
14832
14833
void ImGui::DockContextEndFrame(ImGuiContext* ctx)
14834
34.4k
{
14835
    // Draw backgrounds of node missing their window
14836
34.4k
    ImGuiContext& g = *ctx;
14837
34.4k
    ImGuiDockContext* dc = &g.DockContext;
14838
34.4k
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
14839
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
14840
0
            if (node->LastFrameActive == g.FrameCount && node->IsVisible && node->HostWindow && node->IsLeafNode() && !node->IsBgDrawnThisFrame)
14841
0
            {
14842
0
                ImRect bg_rect(node->Pos + ImVec2(0.0f, GetFrameHeight()), node->Pos + node->Size);
14843
0
                ImDrawFlags bg_rounding_flags = CalcRoundingFlagsForRectInRect(bg_rect, node->HostWindow->Rect(), DOCKING_SPLITTER_SIZE);
14844
0
                node->HostWindow->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
14845
0
                node->HostWindow->DrawList->AddRectFilled(bg_rect.Min, bg_rect.Max, node->LastBgColor, node->HostWindow->WindowRounding, bg_rounding_flags);
14846
0
            }
14847
34.4k
}
14848
14849
ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
14850
0
{
14851
0
    return (ImGuiDockNode*)ctx->DockContext.Nodes.GetVoidPtr(id);
14852
0
}
14853
14854
ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
14855
0
{
14856
    // Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
14857
    // FIXME-OPT FIXME-DOCK: This is suboptimal, even if the node count is small enough not to be a worry.0
14858
    // We should poke in ctx->Nodes to find a suitable ID faster. Even more so trivial that ctx->Nodes lookup is already sorted.
14859
0
    ImGuiID id = 0x0001;
14860
0
    while (DockContextFindNodeByID(ctx, id) != NULL)
14861
0
        id++;
14862
0
    return id;
14863
0
}
14864
14865
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
14866
0
{
14867
    // Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
14868
0
    ImGuiContext& g = *ctx;
14869
0
    if (id == 0)
14870
0
        id = DockContextGenNodeID(ctx);
14871
0
    else
14872
0
        IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
14873
14874
    // We don't set node->LastFrameAlive on construction. Nodes are always created at all time to reflect .ini settings!
14875
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextAddNode 0x%08X\n", id);
14876
0
    ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
14877
0
    ctx->DockContext.Nodes.SetVoidPtr(node->ID, node);
14878
0
    return node;
14879
0
}
14880
14881
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
14882
0
{
14883
0
    ImGuiContext& g = *ctx;
14884
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14885
14886
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextRemoveNode 0x%08X\n", node->ID);
14887
0
    IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
14888
0
    IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
14889
0
    IM_ASSERT(node->Windows.Size == 0);
14890
14891
0
    if (node->HostWindow)
14892
0
        node->HostWindow->DockNodeAsHost = NULL;
14893
14894
0
    ImGuiDockNode* parent_node = node->ParentNode;
14895
0
    const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
14896
0
    if (merge)
14897
0
    {
14898
0
        IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
14899
0
        ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
14900
0
        DockNodeTreeMerge(&g, parent_node, sibling_node);
14901
0
    }
14902
0
    else
14903
0
    {
14904
0
        for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
14905
0
            if (parent_node->ChildNodes[n] == node)
14906
0
                node->ParentNode->ChildNodes[n] = NULL;
14907
0
        dc->Nodes.SetVoidPtr(node->ID, NULL);
14908
0
        IM_DELETE(node);
14909
0
    }
14910
0
}
14911
14912
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
14913
0
{
14914
0
    const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
14915
0
    const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
14916
0
    return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
14917
0
}
14918
14919
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
14920
struct ImGuiDockContextPruneNodeData
14921
{
14922
    int         CountWindows, CountChildWindows, CountChildNodes;
14923
    ImGuiID     RootId;
14924
0
    ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootId = 0; }
14925
};
14926
14927
// Garbage collect unused nodes (run once at init time)
14928
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
14929
0
{
14930
0
    ImGuiContext& g = *ctx;
14931
0
    ImGuiDockContext* dc  = &ctx->DockContext;
14932
0
    IM_ASSERT(g.Windows.Size == 0);
14933
14934
0
    ImPool<ImGuiDockContextPruneNodeData> pool;
14935
0
    pool.Reserve(dc->NodesSettings.Size);
14936
14937
    // Count child nodes and compute RootID
14938
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14939
0
    {
14940
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14941
0
        ImGuiDockContextPruneNodeData* parent_data = settings->ParentNodeId ? pool.GetByKey(settings->ParentNodeId) : 0;
14942
0
        pool.GetOrAddByKey(settings->ID)->RootId = parent_data ? parent_data->RootId : settings->ID;
14943
0
        if (settings->ParentNodeId)
14944
0
            pool.GetOrAddByKey(settings->ParentNodeId)->CountChildNodes++;
14945
0
    }
14946
14947
    // Count reference to dock ids from dockspaces
14948
    // We track the 'auto-DockNode <- manual-Window <- manual-DockSpace' in order to avoid 'auto-DockNode' being ditched by DockContextPruneUnusedSettingsNodes()
14949
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14950
0
    {
14951
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14952
0
        if (settings->ParentWindowId != 0)
14953
0
            if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->ParentWindowId))
14954
0
                if (window_settings->DockId)
14955
0
                    if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(window_settings->DockId))
14956
0
                        data->CountChildNodes++;
14957
0
    }
14958
14959
    // Count reference to dock ids from window settings
14960
    // We guard against the possibility of an invalid .ini file (RootID may point to a missing node)
14961
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
14962
0
        if (ImGuiID dock_id = settings->DockId)
14963
0
            if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
14964
0
            {
14965
0
                data->CountWindows++;
14966
0
                if (ImGuiDockContextPruneNodeData* data_root = (data->RootId == dock_id) ? data : pool.GetByKey(data->RootId))
14967
0
                    data_root->CountChildWindows++;
14968
0
            }
14969
14970
    // Prune
14971
0
    for (int settings_n = 0; settings_n < dc->NodesSettings.Size; settings_n++)
14972
0
    {
14973
0
        ImGuiDockNodeSettings* settings = &dc->NodesSettings[settings_n];
14974
0
        ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
14975
0
        if (data->CountWindows > 1)
14976
0
            continue;
14977
0
        ImGuiDockContextPruneNodeData* data_root = (data->RootId == settings->ID) ? data : pool.GetByKey(data->RootId);
14978
14979
0
        bool remove = false;
14980
0
        remove |= (data->CountWindows == 1 && settings->ParentNodeId == 0 && data->CountChildNodes == 0 && !(settings->Flags & ImGuiDockNodeFlags_CentralNode));  // Floating root node with only 1 window
14981
0
        remove |= (data->CountWindows == 0 && settings->ParentNodeId == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
14982
0
        remove |= (data_root->CountChildWindows == 0);
14983
0
        if (remove)
14984
0
        {
14985
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextPruneUnusedSettingsNodes: Prune 0x%08X\n", settings->ID);
14986
0
            DockSettingsRemoveNodeReferences(&settings->ID, 1);
14987
0
            settings->ID = 0;
14988
0
        }
14989
0
    }
14990
0
}
14991
14992
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
14993
0
{
14994
    // Build nodes
14995
0
    for (int node_n = 0; node_n < node_settings_count; node_n++)
14996
0
    {
14997
0
        ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
14998
0
        if (settings->ID == 0)
14999
0
            continue;
15000
0
        ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
15001
0
        node->ParentNode = settings->ParentNodeId ? DockContextFindNodeByID(ctx, settings->ParentNodeId) : NULL;
15002
0
        node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
15003
0
        node->Size = ImVec2(settings->Size.x, settings->Size.y);
15004
0
        node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
15005
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_DockNode;
15006
0
        if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
15007
0
            node->ParentNode->ChildNodes[0] = node;
15008
0
        else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
15009
0
            node->ParentNode->ChildNodes[1] = node;
15010
0
        node->SelectedTabId = settings->SelectedTabId;
15011
0
        node->SplitAxis = (ImGuiAxis)settings->SplitAxis;
15012
0
        node->SetLocalFlags(settings->Flags & ImGuiDockNodeFlags_SavedFlagsMask_);
15013
15014
        // Bind host window immediately if it already exist (in case of a rebuild)
15015
        // This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
15016
0
        char host_window_title[20];
15017
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
15018
0
        node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
15019
0
    }
15020
0
}
15021
15022
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
15023
0
{
15024
    // Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
15025
0
    ImGuiContext& g = *ctx;
15026
0
    for (int n = 0; n < g.Windows.Size; n++)
15027
0
    {
15028
0
        ImGuiWindow* window = g.Windows[n];
15029
0
        if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
15030
0
            continue;
15031
0
        if (window->DockNode != NULL)
15032
0
            continue;
15033
15034
0
        ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
15035
0
        IM_ASSERT(node != NULL);   // This should have been called after DockContextBuildNodesFromSettings()
15036
0
        if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
15037
0
            DockNodeAddWindow(node, window, true);
15038
0
    }
15039
0
}
15040
15041
//-----------------------------------------------------------------------------
15042
// Docking: ImGuiDockContext Docking/Undocking functions
15043
//-----------------------------------------------------------------------------
15044
// - DockContextQueueDock()
15045
// - DockContextQueueUndockWindow()
15046
// - DockContextQueueUndockNode()
15047
// - DockContextQueueNotifyRemovedNode()
15048
// - DockContextProcessDock()
15049
// - DockContextProcessUndockWindow()
15050
// - DockContextProcessUndockNode()
15051
// - DockContextCalcDropPosForDocking()
15052
//-----------------------------------------------------------------------------
15053
15054
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
15055
0
{
15056
0
    IM_ASSERT(target != payload);
15057
0
    ImGuiDockRequest req;
15058
0
    req.Type = ImGuiDockRequestType_Dock;
15059
0
    req.DockTargetWindow = target;
15060
0
    req.DockTargetNode = target_node;
15061
0
    req.DockPayload = payload;
15062
0
    req.DockSplitDir = split_dir;
15063
0
    req.DockSplitRatio = split_ratio;
15064
0
    req.DockSplitOuter = split_outer;
15065
0
    ctx->DockContext.Requests.push_back(req);
15066
0
}
15067
15068
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
15069
0
{
15070
0
    ImGuiDockRequest req;
15071
0
    req.Type = ImGuiDockRequestType_Undock;
15072
0
    req.UndockTargetWindow = window;
15073
0
    ctx->DockContext.Requests.push_back(req);
15074
0
}
15075
15076
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15077
0
{
15078
0
    ImGuiDockRequest req;
15079
0
    req.Type = ImGuiDockRequestType_Undock;
15080
0
    req.UndockTargetNode = node;
15081
0
    ctx->DockContext.Requests.push_back(req);
15082
0
}
15083
15084
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
15085
0
{
15086
0
    ImGuiDockContext* dc  = &ctx->DockContext;
15087
0
    for (int n = 0; n < dc->Requests.Size; n++)
15088
0
        if (dc->Requests[n].DockTargetNode == node)
15089
0
            dc->Requests[n].Type = ImGuiDockRequestType_None;
15090
0
}
15091
15092
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
15093
0
{
15094
0
    IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
15095
0
    IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
15096
15097
0
    ImGuiContext& g = *ctx;
15098
0
    IM_UNUSED(g);
15099
15100
0
    ImGuiWindow* payload_window = req->DockPayload;     // Optional
15101
0
    ImGuiWindow* target_window = req->DockTargetWindow;
15102
0
    ImGuiDockNode* node = req->DockTargetNode;
15103
0
    if (payload_window)
15104
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X target '%s' dock window '%s', split_dir %d\n", node ? node->ID : 0, target_window ? target_window->Name : "NULL", payload_window->Name, req->DockSplitDir);
15105
0
    else
15106
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessDock node 0x%08X, split_dir %d\n", node ? node->ID : 0, req->DockSplitDir);
15107
15108
    // Decide which Tab will be selected at the end of the operation
15109
0
    ImGuiID next_selected_id = 0;
15110
0
    ImGuiDockNode* payload_node = NULL;
15111
0
    if (payload_window)
15112
0
    {
15113
0
        payload_node = payload_window->DockNodeAsHost;
15114
0
        payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
15115
0
        if (payload_node && payload_node->IsLeafNode())
15116
0
            next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
15117
0
        if (payload_node == NULL)
15118
0
            next_selected_id = payload_window->TabId;
15119
0
    }
15120
15121
    // FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
15122
    // When processing an interactive split, usually LastFrameAlive will be < g.FrameCount. But DockBuilder operations can make it ==.
15123
0
    if (node)
15124
0
        IM_ASSERT(node->LastFrameAlive <= g.FrameCount);
15125
0
    if (node && target_window && node == target_window->DockNodeAsHost)
15126
0
        IM_ASSERT(node->Windows.Size > 0 || node->IsSplitNode() || node->IsCentralNode());
15127
15128
    // Create new node and add existing window to it
15129
0
    if (node == NULL)
15130
0
    {
15131
0
        node = DockContextAddNode(ctx, 0);
15132
0
        node->Pos = target_window->Pos;
15133
0
        node->Size = target_window->Size;
15134
0
        if (target_window->DockNodeAsHost == NULL)
15135
0
        {
15136
0
            DockNodeAddWindow(node, target_window, true);
15137
0
            node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
15138
0
            target_window->DockIsActive = true;
15139
0
        }
15140
0
    }
15141
15142
0
    ImGuiDir split_dir = req->DockSplitDir;
15143
0
    if (split_dir != ImGuiDir_None)
15144
0
    {
15145
        // Split into two, one side will be our payload node unless we are dropping a loose window
15146
0
        const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
15147
0
        const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
15148
0
        const float split_ratio = req->DockSplitRatio;
15149
0
        DockNodeTreeSplit(ctx, node, split_axis, split_inheritor_child_idx, split_ratio, payload_node);  // payload_node may be NULL here!
15150
0
        ImGuiDockNode* new_node = node->ChildNodes[split_inheritor_child_idx ^ 1];
15151
0
        new_node->HostWindow = node->HostWindow;
15152
0
        node = new_node;
15153
0
    }
15154
0
    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15155
15156
0
    if (node != payload_node)
15157
0
    {
15158
        // Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
15159
0
        if (node->Windows.Size > 0 && node->TabBar == NULL)
15160
0
        {
15161
0
            DockNodeAddTabBar(node);
15162
0
            for (int n = 0; n < node->Windows.Size; n++)
15163
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15164
0
        }
15165
15166
0
        if (payload_node != NULL)
15167
0
        {
15168
            // Transfer full payload node (with 1+ child windows or child nodes)
15169
0
            if (payload_node->IsSplitNode())
15170
0
            {
15171
0
                if (node->Windows.Size > 0)
15172
0
                {
15173
                    // We can dock a split payload into a node that already has windows _only_ if our payload is a node tree with a single visible node.
15174
                    // In this situation, we move the windows of the target node into the currently visible node of the payload.
15175
                    // This allows us to preserve some of the underlying dock tree settings nicely.
15176
0
                    IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockSetup() early on and never submitted.
15177
0
                    ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
15178
0
                    if (visible_node->TabBar)
15179
0
                        IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
15180
0
                    DockNodeMoveWindows(node, visible_node);
15181
0
                    DockNodeMoveWindows(visible_node, node);
15182
0
                    DockSettingsRenameNodeReferences(node->ID, visible_node->ID);
15183
0
                }
15184
0
                if (node->IsCentralNode())
15185
0
                {
15186
                    // Central node property needs to be moved to a leaf node, pick the last focused one.
15187
                    // FIXME-DOCK: If we had to transfer other flags here, what would the policy be?
15188
0
                    ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeId);
15189
0
                    IM_ASSERT(last_focused_node != NULL);
15190
0
                    ImGuiDockNode* last_focused_root_node = DockNodeGetRootNode(last_focused_node);
15191
0
                    IM_ASSERT(last_focused_root_node == DockNodeGetRootNode(payload_node));
15192
0
                    last_focused_node->SetLocalFlags(last_focused_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
15193
0
                    node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_CentralNode);
15194
0
                    last_focused_root_node->CentralNode = last_focused_node;
15195
0
                }
15196
15197
0
                IM_ASSERT(node->Windows.Size == 0);
15198
0
                DockNodeMoveChildNodes(node, payload_node);
15199
0
            }
15200
0
            else
15201
0
            {
15202
0
                const ImGuiID payload_dock_id = payload_node->ID;
15203
0
                DockNodeMoveWindows(node, payload_node);
15204
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15205
0
            }
15206
0
            DockContextRemoveNode(ctx, payload_node, true);
15207
0
        }
15208
0
        else if (payload_window)
15209
0
        {
15210
            // Transfer single window
15211
0
            const ImGuiID payload_dock_id = payload_window->DockId;
15212
0
            node->VisibleWindow = payload_window;
15213
0
            DockNodeAddWindow(node, payload_window, true);
15214
0
            if (payload_dock_id != 0)
15215
0
                DockSettingsRenameNodeReferences(payload_dock_id, node->ID);
15216
0
        }
15217
0
    }
15218
0
    else
15219
0
    {
15220
        // When docking a floating single window node we want to reevaluate auto-hiding of the tab bar
15221
0
        node->WantHiddenTabBarUpdate = true;
15222
0
    }
15223
15224
    // Update selection immediately
15225
0
    if (ImGuiTabBar* tab_bar = node->TabBar)
15226
0
        tab_bar->NextSelectedTabId = next_selected_id;
15227
0
    MarkIniSettingsDirty();
15228
0
}
15229
15230
// Problem:
15231
//   Undocking a large (~full screen) window would leave it so large that the bottom right sizing corner would more
15232
//   than likely be off the screen and the window would be hard to resize to fit on screen. This can be particularly problematic
15233
//   with 'ConfigWindowsMoveFromTitleBarOnly=true' and/or with 'ConfigWindowsResizeFromEdges=false' as well (the later can be
15234
//   due to missing ImGuiBackendFlags_HasMouseCursors backend flag).
15235
// Solution:
15236
//   When undocking a window we currently force its maximum size to 90% of the host viewport or monitor.
15237
// Reevaluate this when we implement preserving docked/undocked size ("docking_wip/undocked_size" branch).
15238
static ImVec2 FixLargeWindowsWhenUndocking(const ImVec2& size, ImGuiViewport* ref_viewport)
15239
0
{
15240
0
    if (ref_viewport == NULL)
15241
0
        return size;
15242
15243
0
    ImGuiContext& g = *GImGui;
15244
0
    ImVec2 max_size = ImFloor(ref_viewport->WorkSize * 0.90f);
15245
0
    if (g.ConfigFlagsCurrFrame & ImGuiConfigFlags_ViewportsEnable)
15246
0
    {
15247
0
        const ImGuiPlatformMonitor* monitor = ImGui::GetViewportPlatformMonitor(ref_viewport);
15248
0
        max_size = ImFloor(monitor->WorkSize * 0.90f);
15249
0
    }
15250
0
    return ImMin(size, max_size);
15251
0
}
15252
15253
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
15254
0
{
15255
0
    ImGuiContext& g = *ctx;
15256
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockWindow window '%s', clear_persistent_docking_ref = %d\n", window->Name, clear_persistent_docking_ref);
15257
0
    if (window->DockNode)
15258
0
        DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
15259
0
    else
15260
0
        window->DockId = 0;
15261
0
    window->Collapsed = false;
15262
0
    window->DockIsActive = false;
15263
0
    window->DockNodeIsVisible = window->DockTabIsVisible = false;
15264
0
    window->Size = window->SizeFull = FixLargeWindowsWhenUndocking(window->SizeFull, window->Viewport);
15265
15266
0
    MarkIniSettingsDirty();
15267
0
}
15268
15269
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
15270
0
{
15271
0
    ImGuiContext& g = *ctx;
15272
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockContextProcessUndockNode node %08X\n", node->ID);
15273
0
    IM_ASSERT(node->IsLeafNode());
15274
0
    IM_ASSERT(node->Windows.Size >= 1);
15275
15276
0
    if (node->IsRootNode() || node->IsCentralNode())
15277
0
    {
15278
        // In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
15279
0
        ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
15280
0
        new_node->Pos = node->Pos;
15281
0
        new_node->Size = node->Size;
15282
0
        new_node->SizeRef = node->SizeRef;
15283
0
        DockNodeMoveWindows(new_node, node);
15284
0
        DockSettingsRenameNodeReferences(node->ID, new_node->ID);
15285
0
        node = new_node;
15286
0
    }
15287
0
    else
15288
0
    {
15289
        // Otherwise extract our node and merge our sibling back into the parent node.
15290
0
        IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15291
0
        int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
15292
0
        node->ParentNode->ChildNodes[index_in_parent] = NULL;
15293
0
        DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
15294
0
        node->ParentNode->AuthorityForViewport = ImGuiDataAuthority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
15295
0
        node->ParentNode = NULL;
15296
0
    }
15297
0
    for (int n = 0; n < node->Windows.Size; n++)
15298
0
    {
15299
0
        ImGuiWindow* window = node->Windows[n];
15300
0
        window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15301
0
        if (window->ParentWindow)
15302
0
            window->ParentWindow->DC.ChildWindows.find_erase(window);
15303
0
        UpdateWindowParentAndRootLinks(window, window->Flags, NULL);
15304
0
    }
15305
0
    node->AuthorityForPos = node->AuthorityForSize = ImGuiDataAuthority_DockNode;
15306
0
    node->Size = FixLargeWindowsWhenUndocking(node->Size, node->Windows[0]->Viewport);
15307
0
    node->WantMouseMove = true;
15308
0
    MarkIniSettingsDirty();
15309
0
}
15310
15311
// This is mostly used for automation.
15312
bool ImGui::DockContextCalcDropPosForDocking(ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDir split_dir, bool split_outer, ImVec2* out_pos)
15313
0
{
15314
    // In DockNodePreviewDockSetup() for a root central node instead of showing both "inner" and "outer" drop rects
15315
    // (which would be functionally identical) we only show the outer one. Reflect this here.
15316
0
    if (target_node && target_node->ParentNode == NULL && target_node->IsCentralNode() && split_dir != ImGuiDir_None)
15317
0
        split_outer = true;
15318
0
    ImGuiDockPreviewData split_data;
15319
0
    DockNodePreviewDockSetup(target, target_node, payload_window, payload_node, &split_data, false, split_outer);
15320
0
    if (split_data.DropRectsDraw[split_dir+1].IsInverted())
15321
0
        return false;
15322
0
    *out_pos = split_data.DropRectsDraw[split_dir+1].GetCenter();
15323
0
    return true;
15324
0
}
15325
15326
//-----------------------------------------------------------------------------
15327
// Docking: ImGuiDockNode
15328
//-----------------------------------------------------------------------------
15329
// - DockNodeGetTabOrder()
15330
// - DockNodeAddWindow()
15331
// - DockNodeRemoveWindow()
15332
// - DockNodeMoveChildNodes()
15333
// - DockNodeMoveWindows()
15334
// - DockNodeApplyPosSizeToWindows()
15335
// - DockNodeHideHostWindow()
15336
// - ImGuiDockNodeFindInfoResults
15337
// - DockNodeFindInfo()
15338
// - DockNodeFindWindowByID()
15339
// - DockNodeUpdateFlagsAndCollapse()
15340
// - DockNodeUpdateHasCentralNodeFlag()
15341
// - DockNodeUpdateVisibleFlag()
15342
// - DockNodeStartMouseMovingWindow()
15343
// - DockNodeUpdate()
15344
// - DockNodeUpdateWindowMenu()
15345
// - DockNodeBeginAmendTabBar()
15346
// - DockNodeEndAmendTabBar()
15347
// - DockNodeUpdateTabBar()
15348
// - DockNodeAddTabBar()
15349
// - DockNodeRemoveTabBar()
15350
// - DockNodeIsDropAllowedOne()
15351
// - DockNodeIsDropAllowed()
15352
// - DockNodeCalcTabBarLayout()
15353
// - DockNodeCalcSplitRects()
15354
// - DockNodeCalcDropRectsAndTestMousePos()
15355
// - DockNodePreviewDockSetup()
15356
// - DockNodePreviewDockRender()
15357
//-----------------------------------------------------------------------------
15358
15359
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
15360
0
{
15361
0
    ID = id;
15362
0
    SharedFlags = LocalFlags = LocalFlagsInWindows = MergedFlags = ImGuiDockNodeFlags_None;
15363
0
    ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
15364
0
    TabBar = NULL;
15365
0
    SplitAxis = ImGuiAxis_None;
15366
15367
0
    State = ImGuiDockNodeState_Unknown;
15368
0
    LastBgColor = IM_COL32_WHITE;
15369
0
    HostWindow = VisibleWindow = NULL;
15370
0
    CentralNode = OnlyNodeWithWindows = NULL;
15371
0
    CountNodeWithWindows = 0;
15372
0
    LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
15373
0
    LastFocusedNodeId = 0;
15374
0
    SelectedTabId = 0;
15375
0
    WantCloseTabId = 0;
15376
0
    AuthorityForPos = AuthorityForSize = ImGuiDataAuthority_DockNode;
15377
0
    AuthorityForViewport = ImGuiDataAuthority_Auto;
15378
0
    IsVisible = true;
15379
0
    IsFocused = HasCloseButton = HasWindowMenuButton = HasCentralNodeChild = false;
15380
0
    IsBgDrawnThisFrame = false;
15381
0
    WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
15382
0
}
15383
15384
ImGuiDockNode::~ImGuiDockNode()
15385
0
{
15386
0
    IM_DELETE(TabBar);
15387
0
    TabBar = NULL;
15388
0
    ChildNodes[0] = ChildNodes[1] = NULL;
15389
0
}
15390
15391
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
15392
0
{
15393
0
    ImGuiTabBar* tab_bar = window->DockNode->TabBar;
15394
0
    if (tab_bar == NULL)
15395
0
        return -1;
15396
0
    ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->TabId);
15397
0
    return tab ? TabBarGetTabOrder(tab_bar, tab) : -1;
15398
0
}
15399
15400
static void DockNodeHideWindowDuringHostWindowCreation(ImGuiWindow* window)
15401
0
{
15402
0
    window->Hidden = true;
15403
0
    window->HiddenFramesCanSkipItems = window->Active ? 1 : 2;
15404
0
}
15405
15406
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
15407
0
{
15408
0
    ImGuiContext& g = *GImGui; (void)g;
15409
0
    if (window->DockNode)
15410
0
    {
15411
        // Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
15412
0
        IM_ASSERT(window->DockNode->ID != node->ID);
15413
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
15414
0
    }
15415
0
    IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
15416
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeAddWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15417
15418
    // If more than 2 windows appeared on the same frame leading to the creation of a new hosting window,
15419
    // we'll hide windows until the host window is ready. Hide the 1st window after its been output (so it is not visible for one frame).
15420
    // We will call DockNodeHideWindowDuringHostWindowCreation() on ourselves in Begin()
15421
0
    if (node->HostWindow == NULL && node->Windows.Size == 1 && node->Windows[0]->WasActive == false)
15422
0
        DockNodeHideWindowDuringHostWindowCreation(node->Windows[0]);
15423
15424
0
    node->Windows.push_back(window);
15425
0
    node->WantHiddenTabBarUpdate = true;
15426
0
    window->DockNode = node;
15427
0
    window->DockId = node->ID;
15428
0
    window->DockIsActive = (node->Windows.Size > 1);
15429
0
    window->DockTabWantClose = false;
15430
15431
    // When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
15432
    // In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
15433
0
    if (node->HostWindow == NULL && node->IsFloatingNode())
15434
0
    {
15435
0
        if (node->AuthorityForPos == ImGuiDataAuthority_Auto)
15436
0
            node->AuthorityForPos = ImGuiDataAuthority_Window;
15437
0
        if (node->AuthorityForSize == ImGuiDataAuthority_Auto)
15438
0
            node->AuthorityForSize = ImGuiDataAuthority_Window;
15439
0
        if (node->AuthorityForViewport == ImGuiDataAuthority_Auto)
15440
0
            node->AuthorityForViewport = ImGuiDataAuthority_Window;
15441
0
    }
15442
15443
    // Add to tab bar if requested
15444
0
    if (add_to_tab_bar)
15445
0
    {
15446
0
        if (node->TabBar == NULL)
15447
0
        {
15448
0
            DockNodeAddTabBar(node);
15449
0
            node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabId;
15450
15451
            // Add existing windows
15452
0
            for (int n = 0; n < node->Windows.Size - 1; n++)
15453
0
                TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
15454
0
        }
15455
0
        TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
15456
0
    }
15457
15458
0
    DockNodeUpdateVisibleFlag(node);
15459
15460
    // Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
15461
0
    if (node->HostWindow)
15462
0
        UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
15463
0
}
15464
15465
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
15466
0
{
15467
0
    ImGuiContext& g = *GImGui;
15468
0
    IM_ASSERT(window->DockNode == node);
15469
    //IM_ASSERT(window->RootWindowDockTree == node->HostWindow);
15470
    //IM_ASSERT(window->LastFrameActive < g.FrameCount);    // We may call this from Begin()
15471
0
    IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
15472
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeRemoveWindow node 0x%08X window '%s'\n", node->ID, window->Name);
15473
15474
0
    window->DockNode = NULL;
15475
0
    window->DockIsActive = window->DockTabWantClose = false;
15476
0
    window->DockId = save_dock_id;
15477
0
    window->Flags &= ~ImGuiWindowFlags_ChildWindow;
15478
0
    if (window->ParentWindow)
15479
0
        window->ParentWindow->DC.ChildWindows.find_erase(window);
15480
0
    UpdateWindowParentAndRootLinks(window, window->Flags, NULL); // Update immediately
15481
15482
    // Remove window
15483
0
    bool erased = false;
15484
0
    for (int n = 0; n < node->Windows.Size; n++)
15485
0
        if (node->Windows[n] == window)
15486
0
        {
15487
0
            node->Windows.erase(node->Windows.Data + n);
15488
0
            erased = true;
15489
0
            break;
15490
0
        }
15491
0
    if (!erased)
15492
0
        IM_ASSERT(erased);
15493
0
    if (node->VisibleWindow == window)
15494
0
        node->VisibleWindow = NULL;
15495
15496
    // Remove tab and possibly tab bar
15497
0
    node->WantHiddenTabBarUpdate = true;
15498
0
    if (node->TabBar)
15499
0
    {
15500
0
        TabBarRemoveTab(node->TabBar, window->TabId);
15501
0
        const int tab_count_threshold_for_tab_bar = node->IsCentralNode() ? 1 : 2;
15502
0
        if (node->Windows.Size < tab_count_threshold_for_tab_bar)
15503
0
            DockNodeRemoveTabBar(node);
15504
0
    }
15505
15506
0
    if (node->Windows.Size == 0 && !node->IsCentralNode() && !node->IsDockSpace() && window->DockId != node->ID)
15507
0
    {
15508
        // Automatic dock node delete themselves if they are not holding at least one tab
15509
0
        DockContextRemoveNode(&g, node, true);
15510
0
        return;
15511
0
    }
15512
15513
0
    if (node->Windows.Size == 1 && !node->IsCentralNode() && node->HostWindow)
15514
0
    {
15515
0
        ImGuiWindow* remaining_window = node->Windows[0];
15516
0
        if (node->HostWindow->ViewportOwned && node->IsRootNode())
15517
0
        {
15518
            // Transfer viewport back to the remaining loose window
15519
0
            IMGUI_DEBUG_LOG_VIEWPORT("[viewport] Node %08X transfer Viewport %08X=>%08X for Window '%s'\n", node->ID, node->HostWindow->Viewport->ID, remaining_window->ID, remaining_window->Name);
15520
0
            IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
15521
0
            node->HostWindow->Viewport->Window = remaining_window;
15522
0
            node->HostWindow->Viewport->ID = remaining_window->ID;
15523
0
        }
15524
0
        remaining_window->Collapsed = node->HostWindow->Collapsed;
15525
0
    }
15526
15527
    // Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
15528
0
    DockNodeUpdateVisibleFlag(node);
15529
0
}
15530
15531
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15532
0
{
15533
0
    IM_ASSERT(dst_node->Windows.Size == 0);
15534
0
    dst_node->ChildNodes[0] = src_node->ChildNodes[0];
15535
0
    dst_node->ChildNodes[1] = src_node->ChildNodes[1];
15536
0
    if (dst_node->ChildNodes[0])
15537
0
        dst_node->ChildNodes[0]->ParentNode = dst_node;
15538
0
    if (dst_node->ChildNodes[1])
15539
0
        dst_node->ChildNodes[1]->ParentNode = dst_node;
15540
0
    dst_node->SplitAxis = src_node->SplitAxis;
15541
0
    dst_node->SizeRef = src_node->SizeRef;
15542
0
    src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
15543
0
}
15544
15545
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
15546
0
{
15547
    // Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
15548
0
    IM_ASSERT(src_node && dst_node && dst_node != src_node);
15549
0
    ImGuiTabBar* src_tab_bar = src_node->TabBar;
15550
0
    if (src_tab_bar != NULL)
15551
0
        IM_ASSERT(src_node->Windows.Size <= src_node->TabBar->Tabs.Size);
15552
15553
    // If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
15554
0
    bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
15555
0
    if (move_tab_bar)
15556
0
    {
15557
0
        dst_node->TabBar = src_node->TabBar;
15558
0
        src_node->TabBar = NULL;
15559
0
    }
15560
15561
    // Tab order is not important here, it is preserved by sorting in DockNodeUpdateTabBar().
15562
0
    for (ImGuiWindow* window : src_node->Windows)
15563
0
    {
15564
0
        window->DockNode = NULL;
15565
0
        window->DockIsActive = false;
15566
0
        DockNodeAddWindow(dst_node, window, !move_tab_bar);
15567
0
    }
15568
0
    src_node->Windows.clear();
15569
15570
0
    if (!move_tab_bar && src_node->TabBar)
15571
0
    {
15572
0
        if (dst_node->TabBar)
15573
0
            dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
15574
0
        DockNodeRemoveTabBar(src_node);
15575
0
    }
15576
0
}
15577
15578
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
15579
0
{
15580
0
    for (int n = 0; n < node->Windows.Size; n++)
15581
0
    {
15582
0
        SetWindowPos(node->Windows[n], node->Pos, ImGuiCond_Always); // We don't assign directly to Pos because it can break the calculation of SizeContents on next frame
15583
0
        SetWindowSize(node->Windows[n], node->Size, ImGuiCond_Always);
15584
0
    }
15585
0
}
15586
15587
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
15588
0
{
15589
0
    if (node->HostWindow)
15590
0
    {
15591
0
        if (node->HostWindow->DockNodeAsHost == node)
15592
0
            node->HostWindow->DockNodeAsHost = NULL;
15593
0
        node->HostWindow = NULL;
15594
0
    }
15595
15596
0
    if (node->Windows.Size == 1)
15597
0
    {
15598
0
        node->VisibleWindow = node->Windows[0];
15599
0
        node->Windows[0]->DockIsActive = false;
15600
0
    }
15601
15602
0
    if (node->TabBar)
15603
0
        DockNodeRemoveTabBar(node);
15604
0
}
15605
15606
// Search function called once by root node in DockNodeUpdate()
15607
struct ImGuiDockNodeTreeInfo
15608
{
15609
    ImGuiDockNode*      CentralNode;
15610
    ImGuiDockNode*      FirstNodeWithWindows;
15611
    int                 CountNodesWithWindows;
15612
    //ImGuiWindowClass  WindowClassForMerges;
15613
15614
0
    ImGuiDockNodeTreeInfo() { memset(this, 0, sizeof(*this)); }
15615
};
15616
15617
static void DockNodeFindInfo(ImGuiDockNode* node, ImGuiDockNodeTreeInfo* info)
15618
0
{
15619
0
    if (node->Windows.Size > 0)
15620
0
    {
15621
0
        if (info->FirstNodeWithWindows == NULL)
15622
0
            info->FirstNodeWithWindows = node;
15623
0
        info->CountNodesWithWindows++;
15624
0
    }
15625
0
    if (node->IsCentralNode())
15626
0
    {
15627
0
        IM_ASSERT(info->CentralNode == NULL); // Should be only one
15628
0
        IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
15629
0
        info->CentralNode = node;
15630
0
    }
15631
0
    if (info->CountNodesWithWindows > 1 && info->CentralNode != NULL)
15632
0
        return;
15633
0
    if (node->ChildNodes[0])
15634
0
        DockNodeFindInfo(node->ChildNodes[0], info);
15635
0
    if (node->ChildNodes[1])
15636
0
        DockNodeFindInfo(node->ChildNodes[1], info);
15637
0
}
15638
15639
static ImGuiWindow* ImGui::DockNodeFindWindowByID(ImGuiDockNode* node, ImGuiID id)
15640
0
{
15641
0
    IM_ASSERT(id != 0);
15642
0
    for (int n = 0; n < node->Windows.Size; n++)
15643
0
        if (node->Windows[n]->ID == id)
15644
0
            return node->Windows[n];
15645
0
    return NULL;
15646
0
}
15647
15648
// - Remove inactive windows/nodes.
15649
// - Update visibility flag.
15650
static void ImGui::DockNodeUpdateFlagsAndCollapse(ImGuiDockNode* node)
15651
0
{
15652
0
    ImGuiContext& g = *GImGui;
15653
0
    IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
15654
15655
    // Inherit most flags
15656
0
    if (node->ParentNode)
15657
0
        node->SharedFlags = node->ParentNode->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
15658
15659
    // Recurse into children
15660
    // There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
15661
    // If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
15662
    // If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
15663
0
    node->HasCentralNodeChild = false;
15664
0
    if (node->ChildNodes[0])
15665
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[0]);
15666
0
    if (node->ChildNodes[1])
15667
0
        DockNodeUpdateFlagsAndCollapse(node->ChildNodes[1]);
15668
15669
    // Remove inactive windows, collapse nodes
15670
    // Merge node flags overrides stored in windows
15671
0
    node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
15672
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15673
0
    {
15674
0
        ImGuiWindow* window = node->Windows[window_n];
15675
0
        IM_ASSERT(window->DockNode == node);
15676
15677
0
        bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
15678
0
        bool remove = false;
15679
0
        remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
15680
0
        remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabId == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument);  // Submit all _expected_ closure from last frame
15681
0
        remove |= (window->DockTabWantClose);
15682
0
        if (remove)
15683
0
        {
15684
0
            window->DockTabWantClose = false;
15685
0
            if (node->Windows.Size == 1 && !node->IsCentralNode())
15686
0
            {
15687
0
                DockNodeHideHostWindow(node);
15688
0
                node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15689
0
                DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
15690
0
                return;
15691
0
            }
15692
0
            DockNodeRemoveWindow(node, window, node->ID);
15693
0
            window_n--;
15694
0
            continue;
15695
0
        }
15696
15697
        // FIXME-DOCKING: Missing policies for conflict resolution, hence the "Experimental" tag on this.
15698
        //node->LocalFlagsInWindow &= ~window->WindowClass.DockNodeFlagsOverrideClear;
15699
0
        node->LocalFlagsInWindows |= window->WindowClass.DockNodeFlagsOverrideSet;
15700
0
    }
15701
0
    node->UpdateMergedFlags();
15702
15703
    // Auto-hide tab bar option
15704
0
    ImGuiDockNodeFlags node_flags = node->MergedFlags;
15705
0
    if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node_flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar())
15706
0
        node->WantHiddenTabBarToggle = true;
15707
0
    node->WantHiddenTabBarUpdate = false;
15708
15709
    // Cancel toggling if we know our tab bar is enforced to be hidden at all times
15710
0
    if (node->WantHiddenTabBarToggle && node->VisibleWindow && (node->VisibleWindow->WindowClass.DockNodeFlagsOverrideSet & ImGuiDockNodeFlags_HiddenTabBar))
15711
0
        node->WantHiddenTabBarToggle = false;
15712
15713
    // Apply toggles at a single point of the frame (here!)
15714
0
    if (node->Windows.Size > 1)
15715
0
        node->SetLocalFlags(node->LocalFlags & ~ImGuiDockNodeFlags_HiddenTabBar);
15716
0
    else if (node->WantHiddenTabBarToggle)
15717
0
        node->SetLocalFlags(node->LocalFlags ^ ImGuiDockNodeFlags_HiddenTabBar);
15718
0
    node->WantHiddenTabBarToggle = false;
15719
15720
0
    DockNodeUpdateVisibleFlag(node);
15721
0
}
15722
15723
// This is rarely called as DockNodeUpdateForRootNode() generally does it most frames.
15724
static void ImGui::DockNodeUpdateHasCentralNodeChild(ImGuiDockNode* node)
15725
0
{
15726
0
    node->HasCentralNodeChild = false;
15727
0
    if (node->ChildNodes[0])
15728
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[0]);
15729
0
    if (node->ChildNodes[1])
15730
0
        DockNodeUpdateHasCentralNodeChild(node->ChildNodes[1]);
15731
0
    if (node->IsRootNode())
15732
0
    {
15733
0
        ImGuiDockNode* mark_node = node->CentralNode;
15734
0
        while (mark_node)
15735
0
        {
15736
0
            mark_node->HasCentralNodeChild = true;
15737
0
            mark_node = mark_node->ParentNode;
15738
0
        }
15739
0
    }
15740
0
}
15741
15742
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
15743
0
{
15744
    // Update visibility flag
15745
0
    bool is_visible = (node->ParentNode == NULL) ? node->IsDockSpace() : node->IsCentralNode();
15746
0
    is_visible |= (node->Windows.Size > 0);
15747
0
    is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
15748
0
    is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
15749
0
    node->IsVisible = is_visible;
15750
0
}
15751
15752
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
15753
0
{
15754
0
    ImGuiContext& g = *GImGui;
15755
0
    IM_ASSERT(node->WantMouseMove == true);
15756
0
    StartMouseMovingWindow(window);
15757
0
    g.ActiveIdClickOffset = g.IO.MouseClickedPos[0] - node->Pos;
15758
0
    g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
15759
0
    node->WantMouseMove = false;
15760
0
}
15761
15762
// Update CentralNode, OnlyNodeWithWindows, LastFocusedNodeID. Copy window class.
15763
static void ImGui::DockNodeUpdateForRootNode(ImGuiDockNode* node)
15764
0
{
15765
0
    DockNodeUpdateFlagsAndCollapse(node);
15766
15767
    // - Setup central node pointers
15768
    // - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
15769
    // Cannot merge this with DockNodeUpdateFlagsAndCollapse() because FirstNodeWithWindows is found after window removal and child collapsing
15770
0
    ImGuiDockNodeTreeInfo info;
15771
0
    DockNodeFindInfo(node, &info);
15772
0
    node->CentralNode = info.CentralNode;
15773
0
    node->OnlyNodeWithWindows = (info.CountNodesWithWindows == 1) ? info.FirstNodeWithWindows : NULL;
15774
0
    node->CountNodeWithWindows = info.CountNodesWithWindows;
15775
0
    if (node->LastFocusedNodeId == 0 && info.FirstNodeWithWindows != NULL)
15776
0
        node->LastFocusedNodeId = info.FirstNodeWithWindows->ID;
15777
15778
    // Copy the window class from of our first window so it can be used for proper dock filtering.
15779
    // When node has mixed windows, prioritize the class with the most constraint (DockingAllowUnclassed = false) as the reference to copy.
15780
    // FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
15781
0
    if (ImGuiDockNode* first_node_with_windows = info.FirstNodeWithWindows)
15782
0
    {
15783
0
        node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
15784
0
        for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
15785
0
            if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
15786
0
            {
15787
0
                node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
15788
0
                break;
15789
0
            }
15790
0
    }
15791
15792
0
    ImGuiDockNode* mark_node = node->CentralNode;
15793
0
    while (mark_node)
15794
0
    {
15795
0
        mark_node->HasCentralNodeChild = true;
15796
0
        mark_node = mark_node->ParentNode;
15797
0
    }
15798
0
}
15799
15800
static void DockNodeSetupHostWindow(ImGuiDockNode* node, ImGuiWindow* host_window)
15801
0
{
15802
    // Remove ourselves from any previous different host window
15803
    // This can happen if a user mistakenly does (see #4295 for details):
15804
    //  - N+0: DockBuilderAddNode(id, 0)    // missing ImGuiDockNodeFlags_DockSpace
15805
    //  - N+1: NewFrame()                   // will create floating host window for that node
15806
    //  - N+1: DockSpace(id)                // requalify node as dockspace, moving host window
15807
0
    if (node->HostWindow && node->HostWindow != host_window && node->HostWindow->DockNodeAsHost == node)
15808
0
        node->HostWindow->DockNodeAsHost = NULL;
15809
15810
0
    host_window->DockNodeAsHost = node;
15811
0
    node->HostWindow = host_window;
15812
0
}
15813
15814
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
15815
0
{
15816
0
    ImGuiContext& g = *GImGui;
15817
0
    IM_ASSERT(node->LastFrameActive != g.FrameCount);
15818
0
    node->LastFrameAlive = g.FrameCount;
15819
0
    node->IsBgDrawnThisFrame = false;
15820
15821
0
    node->CentralNode = node->OnlyNodeWithWindows = NULL;
15822
0
    if (node->IsRootNode())
15823
0
        DockNodeUpdateForRootNode(node);
15824
15825
    // Remove tab bar if not needed
15826
0
    if (node->TabBar && node->IsNoTabBar())
15827
0
        DockNodeRemoveTabBar(node);
15828
15829
    // Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
15830
0
    bool want_to_hide_host_window = false;
15831
0
    if (node->IsFloatingNode())
15832
0
    {
15833
0
        if (node->Windows.Size <= 1 && node->IsLeafNode())
15834
0
            if (!g.IO.ConfigDockingAlwaysTabBar && (node->Windows.Size == 0 || !node->Windows[0]->WindowClass.DockingAlwaysTabBar))
15835
0
                want_to_hide_host_window = true;
15836
0
        if (node->CountNodeWithWindows == 0)
15837
0
            want_to_hide_host_window = true;
15838
0
    }
15839
0
    if (want_to_hide_host_window)
15840
0
    {
15841
0
        if (node->Windows.Size == 1)
15842
0
        {
15843
            // Floating window pos/size is authoritative
15844
0
            ImGuiWindow* single_window = node->Windows[0];
15845
0
            node->Pos = single_window->Pos;
15846
0
            node->Size = single_window->SizeFull;
15847
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
15848
15849
            // Transfer focus immediately so when we revert to a regular window it is immediately selected
15850
0
            if (node->HostWindow && g.NavWindow == node->HostWindow)
15851
0
                FocusWindow(single_window);
15852
0
            if (node->HostWindow)
15853
0
            {
15854
0
                single_window->Viewport = node->HostWindow->Viewport;
15855
0
                single_window->ViewportId = node->HostWindow->ViewportId;
15856
0
                if (node->HostWindow->ViewportOwned)
15857
0
                {
15858
0
                    single_window->Viewport->Window = single_window;
15859
0
                    single_window->ViewportOwned = true;
15860
0
                }
15861
0
            }
15862
0
        }
15863
15864
0
        DockNodeHideHostWindow(node);
15865
0
        node->State = ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow;
15866
0
        node->WantCloseAll = false;
15867
0
        node->WantCloseTabId = 0;
15868
0
        node->HasCloseButton = node->HasWindowMenuButton = false;
15869
0
        node->LastFrameActive = g.FrameCount;
15870
15871
0
        if (node->WantMouseMove && node->Windows.Size == 1)
15872
0
            DockNodeStartMouseMovingWindow(node, node->Windows[0]);
15873
0
        return;
15874
0
    }
15875
15876
    // In some circumstance we will defer creating the host window (so everything will be kept hidden),
15877
    // while the expected visible window is resizing itself.
15878
    // This is important for first-time (no ini settings restored) single window when io.ConfigDockingAlwaysTabBar is enabled,
15879
    // otherwise the node ends up using the minimum window size. Effectively those windows will take an extra frame to show up:
15880
    //   N+0: Begin(): window created (with no known size), node is created
15881
    //   N+1: DockNodeUpdate(): node skip creating host window / Begin(): window size applied, not visible
15882
    //   N+2: DockNodeUpdate(): node can create host window / Begin(): window becomes visible
15883
    // We could remove this frame if we could reliably calculate the expected window size during node update, before the Begin() code.
15884
    // It would require a generalization of CalcWindowExpectedSize(), probably extracting code away from Begin().
15885
    // In reality it isn't very important as user quickly ends up with size data in .ini file.
15886
0
    if (node->IsVisible && node->HostWindow == NULL && node->IsFloatingNode() && node->IsLeafNode())
15887
0
    {
15888
0
        IM_ASSERT(node->Windows.Size > 0);
15889
0
        ImGuiWindow* ref_window = NULL;
15890
0
        if (node->SelectedTabId != 0) // Note that we prune single-window-node settings on .ini loading, so this is generally 0 for them!
15891
0
            ref_window = DockNodeFindWindowByID(node, node->SelectedTabId);
15892
0
        if (ref_window == NULL)
15893
0
            ref_window = node->Windows[0];
15894
0
        if (ref_window->AutoFitFramesX > 0 || ref_window->AutoFitFramesY > 0)
15895
0
        {
15896
0
            node->State = ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing;
15897
0
            return;
15898
0
        }
15899
0
    }
15900
15901
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
15902
15903
    // Decide if the node will have a close button and a window menu button
15904
0
    node->HasWindowMenuButton = (node->Windows.Size > 0) && (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0;
15905
0
    node->HasCloseButton = false;
15906
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
15907
0
    {
15908
        // FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
15909
0
        ImGuiWindow* window = node->Windows[window_n];
15910
0
        node->HasCloseButton |= window->HasCloseButton;
15911
0
        window->DockIsActive = (node->Windows.Size > 1);
15912
0
    }
15913
0
    if (node_flags & ImGuiDockNodeFlags_NoCloseButton)
15914
0
        node->HasCloseButton = false;
15915
15916
    // Bind or create host window
15917
0
    ImGuiWindow* host_window = NULL;
15918
0
    bool beginned_into_host_window = false;
15919
0
    if (node->IsDockSpace())
15920
0
    {
15921
        // [Explicit root dockspace node]
15922
0
        IM_ASSERT(node->HostWindow);
15923
0
        host_window = node->HostWindow;
15924
0
    }
15925
0
    else
15926
0
    {
15927
        // [Automatic root or child nodes]
15928
0
        if (node->IsRootNode() && node->IsVisible)
15929
0
        {
15930
0
            ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
15931
15932
            // Sync Pos
15933
0
            if (node->AuthorityForPos == ImGuiDataAuthority_Window && ref_window)
15934
0
                SetNextWindowPos(ref_window->Pos);
15935
0
            else if (node->AuthorityForPos == ImGuiDataAuthority_DockNode)
15936
0
                SetNextWindowPos(node->Pos);
15937
15938
            // Sync Size
15939
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15940
0
                SetNextWindowSize(ref_window->SizeFull);
15941
0
            else if (node->AuthorityForSize == ImGuiDataAuthority_DockNode)
15942
0
                SetNextWindowSize(node->Size);
15943
15944
            // Sync Collapsed
15945
0
            if (node->AuthorityForSize == ImGuiDataAuthority_Window && ref_window)
15946
0
                SetNextWindowCollapsed(ref_window->Collapsed);
15947
15948
            // Sync Viewport
15949
0
            if (node->AuthorityForViewport == ImGuiDataAuthority_Window && ref_window)
15950
0
                SetNextWindowViewport(ref_window->ViewportId);
15951
15952
0
            SetNextWindowClass(&node->WindowClass);
15953
15954
            // Begin into the host window
15955
0
            char window_label[20];
15956
0
            DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
15957
0
            ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
15958
0
            window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
15959
0
            window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
15960
0
            window_flags |= ImGuiWindowFlags_NoTitleBar;
15961
15962
0
            SetNextWindowBgAlpha(0.0f); // Don't set ImGuiWindowFlags_NoBackground because it disables borders
15963
0
            PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
15964
0
            Begin(window_label, NULL, window_flags);
15965
0
            PopStyleVar();
15966
0
            beginned_into_host_window = true;
15967
15968
0
            host_window = g.CurrentWindow;
15969
0
            DockNodeSetupHostWindow(node, host_window);
15970
0
            host_window->DC.CursorPos = host_window->Pos;
15971
0
            node->Pos = host_window->Pos;
15972
0
            node->Size = host_window->Size;
15973
15974
            // We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
15975
            // But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
15976
            // One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
15977
            // When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
15978
            // during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
15979
            // after the dock host window, losing their top-most status.
15980
0
            if (node->HostWindow->Appearing)
15981
0
                BringWindowToDisplayFront(node->HostWindow);
15982
15983
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15984
0
        }
15985
0
        else if (node->ParentNode)
15986
0
        {
15987
0
            node->HostWindow = host_window = node->ParentNode->HostWindow;
15988
0
            node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Auto;
15989
0
        }
15990
0
        if (node->WantMouseMove && node->HostWindow)
15991
0
            DockNodeStartMouseMovingWindow(node, node->HostWindow);
15992
0
    }
15993
15994
    // Update focused node (the one whose title bar is highlight) within a node tree
15995
0
    if (node->IsSplitNode())
15996
0
        IM_ASSERT(node->TabBar == NULL);
15997
0
    if (node->IsRootNode())
15998
0
        if (ImGuiWindow* p_window = g.NavWindow ? g.NavWindow->RootWindow : NULL)
15999
0
            while (p_window != NULL && p_window->DockNode != NULL)
16000
0
            {
16001
0
                ImGuiDockNode* p_node = DockNodeGetRootNode(p_window->DockNode);
16002
0
                if (p_node == node)
16003
0
                {
16004
0
                    node->LastFocusedNodeId = p_window->DockNode->ID; // Note: not using root node ID!
16005
0
                    break;
16006
0
                }
16007
0
                p_window = p_node->HostWindow ? p_node->HostWindow->RootWindow : NULL;
16008
0
            }
16009
16010
    // Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
16011
0
    ImGuiDockNode* central_node = node->CentralNode;
16012
0
    const bool central_node_hole = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0 && central_node != NULL && central_node->IsEmpty();
16013
0
    bool central_node_hole_register_hit_test_hole = central_node_hole;
16014
0
    if (central_node_hole)
16015
0
        if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
16016
0
            if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
16017
0
                central_node_hole_register_hit_test_hole = false;
16018
0
    if (central_node_hole_register_hit_test_hole)
16019
0
    {
16020
        // We add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
16021
        // (But we only add it if there's something else on the other side of the hole, otherwise for e.g. fullscreen
16022
        // covering passthru node we'd have a gap on the edge not covered by the hole)
16023
0
        IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
16024
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(central_node);
16025
0
        ImRect root_rect(root_node->Pos, root_node->Pos + root_node->Size);
16026
0
        ImRect hole_rect(central_node->Pos, central_node->Pos + central_node->Size);
16027
0
        if (hole_rect.Min.x > root_rect.Min.x) { hole_rect.Min.x += WINDOWS_HOVER_PADDING; }
16028
0
        if (hole_rect.Max.x < root_rect.Max.x) { hole_rect.Max.x -= WINDOWS_HOVER_PADDING; }
16029
0
        if (hole_rect.Min.y > root_rect.Min.y) { hole_rect.Min.y += WINDOWS_HOVER_PADDING; }
16030
0
        if (hole_rect.Max.y < root_rect.Max.y) { hole_rect.Max.y -= WINDOWS_HOVER_PADDING; }
16031
        //GetForegroundDrawList()->AddRect(hole_rect.Min, hole_rect.Max, IM_COL32(255, 0, 0, 255));
16032
0
        if (central_node_hole && !hole_rect.IsInverted())
16033
0
        {
16034
0
            SetWindowHitTestHole(host_window, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16035
0
            if (host_window->ParentWindow)
16036
0
                SetWindowHitTestHole(host_window->ParentWindow, hole_rect.Min, hole_rect.Max - hole_rect.Min);
16037
0
        }
16038
0
    }
16039
16040
    // Update position/size, process and draw resizing splitters
16041
0
    if (node->IsRootNode() && host_window)
16042
0
    {
16043
0
        DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
16044
0
        DockNodeTreeUpdateSplitter(node);
16045
0
    }
16046
16047
    // Draw empty node background (currently can only be the Central Node)
16048
0
    if (host_window && node->IsEmpty() && node->IsVisible)
16049
0
    {
16050
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16051
0
        node->LastBgColor = (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) ? 0 : GetColorU32(ImGuiCol_DockingEmptyBg);
16052
0
        if (node->LastBgColor != 0)
16053
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, node->LastBgColor);
16054
0
        node->IsBgDrawnThisFrame = true;
16055
0
    }
16056
16057
    // Draw whole dockspace background if ImGuiDockNodeFlags_PassthruCentralNode if set.
16058
    // We need to draw a background at the root level if requested by ImGuiDockNodeFlags_PassthruCentralNode, but we will only know the correct pos/size
16059
    // _after_ processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
16060
0
    const bool render_dockspace_bg = node->IsRootNode() && host_window && (node_flags & ImGuiDockNodeFlags_PassthruCentralNode) != 0;
16061
0
    if (render_dockspace_bg && node->IsVisible)
16062
0
    {
16063
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_BG);
16064
0
        if (central_node_hole)
16065
0
            RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
16066
0
        else
16067
0
            host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
16068
0
    }
16069
16070
    // Draw and populate Tab Bar
16071
0
    if (host_window)
16072
0
        host_window->DrawList->ChannelsSetCurrent(DOCKING_HOST_DRAW_CHANNEL_FG);
16073
0
    if (host_window && node->Windows.Size > 0)
16074
0
    {
16075
0
        DockNodeUpdateTabBar(node, host_window);
16076
0
    }
16077
0
    else
16078
0
    {
16079
0
        node->WantCloseAll = false;
16080
0
        node->WantCloseTabId = 0;
16081
0
        node->IsFocused = false;
16082
0
    }
16083
0
    if (node->TabBar && node->TabBar->SelectedTabId)
16084
0
        node->SelectedTabId = node->TabBar->SelectedTabId;
16085
0
    else if (node->Windows.Size > 0)
16086
0
        node->SelectedTabId = node->Windows[0]->TabId;
16087
16088
    // Draw payload drop target
16089
0
    if (host_window && node->IsVisible)
16090
0
        if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindowDockTree != host_window))
16091
0
            BeginDockableDragDropTarget(host_window);
16092
16093
    // We update this after DockNodeUpdateTabBar()
16094
0
    node->LastFrameActive = g.FrameCount;
16095
16096
    // Recurse into children
16097
    // FIXME-DOCK FIXME-OPT: Should not need to recurse into children
16098
0
    if (host_window)
16099
0
    {
16100
0
        if (node->ChildNodes[0])
16101
0
            DockNodeUpdate(node->ChildNodes[0]);
16102
0
        if (node->ChildNodes[1])
16103
0
            DockNodeUpdate(node->ChildNodes[1]);
16104
16105
        // Render outer borders last (after the tab bar)
16106
0
        if (node->IsRootNode())
16107
0
            RenderWindowOuterBorders(host_window);
16108
0
    }
16109
16110
    // End host window
16111
0
    if (beginned_into_host_window) //-V1020
16112
0
        End();
16113
0
}
16114
16115
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
16116
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
16117
0
{
16118
0
    ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
16119
0
    ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
16120
0
    if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
16121
0
        return d;
16122
0
    return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
16123
0
}
16124
16125
static ImGuiID ImGui::DockNodeUpdateWindowMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
16126
0
{
16127
    // Try to position the menu so it is more likely to stays within the same viewport
16128
0
    ImGuiContext& g = *GImGui;
16129
0
    ImGuiID ret_tab_id = 0;
16130
0
    if (g.Style.WindowMenuButtonPosition == ImGuiDir_Left)
16131
0
        SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(0.0f, 0.0f));
16132
0
    else
16133
0
        SetNextWindowPos(ImVec2(node->Pos.x + node->Size.x, node->Pos.y + GetFrameHeight()), ImGuiCond_Always, ImVec2(1.0f, 0.0f));
16134
0
    if (BeginPopup("#WindowMenu"))
16135
0
    {
16136
0
        node->IsFocused = true;
16137
0
        if (tab_bar->Tabs.Size == 1)
16138
0
        {
16139
0
            if (MenuItem(LocalizeGetMsg(ImGuiLocKey_DockingHideTabBar), NULL, node->IsHiddenTabBar()))
16140
0
                node->WantHiddenTabBarToggle = true;
16141
0
        }
16142
0
        else
16143
0
        {
16144
0
            for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
16145
0
            {
16146
0
                ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
16147
0
                if (tab->Flags & ImGuiTabItemFlags_Button)
16148
0
                    continue;
16149
0
                if (Selectable(TabBarGetTabName(tab_bar, tab), tab->ID == tab_bar->SelectedTabId))
16150
0
                    ret_tab_id = tab->ID;
16151
0
                SameLine();
16152
0
                Text("   ");
16153
0
            }
16154
0
        }
16155
0
        EndPopup();
16156
0
    }
16157
0
    return ret_tab_id;
16158
0
}
16159
16160
// User helper to append/amend into a dock node tab bar. Most commonly used to add e.g. a "+" button.
16161
bool ImGui::DockNodeBeginAmendTabBar(ImGuiDockNode* node)
16162
0
{
16163
0
    if (node->TabBar == NULL || node->HostWindow == NULL)
16164
0
        return false;
16165
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
16166
0
        return false;
16167
0
    Begin(node->HostWindow->Name);
16168
0
    PushOverrideID(node->ID);
16169
0
    bool ret = BeginTabBarEx(node->TabBar, node->TabBar->BarRect, node->TabBar->Flags, node);
16170
0
    IM_UNUSED(ret);
16171
0
    IM_ASSERT(ret);
16172
0
    return true;
16173
0
}
16174
16175
void ImGui::DockNodeEndAmendTabBar()
16176
0
{
16177
0
    EndTabBar();
16178
0
    PopID();
16179
0
    End();
16180
0
}
16181
16182
static bool IsDockNodeTitleBarHighlighted(ImGuiDockNode* node, ImGuiDockNode* root_node)
16183
0
{
16184
    // CTRL+Tab highlight (only highlighting leaf node, not whole hierarchy)
16185
0
    ImGuiContext& g = *GImGui;
16186
0
    if (g.NavWindowingTarget)
16187
0
        return (g.NavWindowingTarget->DockNode == node);
16188
16189
    // FIXME-DOCKING: May want alternative to treat central node void differently? e.g. if (g.NavWindow == host_window)
16190
0
    if (g.NavWindow && root_node->LastFocusedNodeId == node->ID)
16191
0
    {
16192
        // FIXME: This could all be backed in RootWindowForTitleBarHighlight? Probably need to reorganize for both dock nodes + other RootWindowForTitleBarHighlight users (not-node)
16193
0
        ImGuiWindow* parent_window = g.NavWindow->RootWindow;
16194
0
        while (parent_window->Flags & ImGuiWindowFlags_ChildMenu)
16195
0
            parent_window = parent_window->ParentWindow->RootWindow;
16196
0
        ImGuiDockNode* start_parent_node = parent_window->DockNodeAsHost ? parent_window->DockNodeAsHost : parent_window->DockNode;
16197
0
        for (ImGuiDockNode* parent_node = start_parent_node; parent_node != NULL; parent_node = parent_node->HostWindow ? parent_node->HostWindow->RootWindow->DockNode : NULL)
16198
0
            if ((parent_node = ImGui::DockNodeGetRootNode(parent_node)) == root_node)
16199
0
                return true;
16200
0
    }
16201
0
    return false;
16202
0
}
16203
16204
// Submit the tab bar corresponding to a dock node and various housekeeping details.
16205
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
16206
0
{
16207
0
    ImGuiContext& g = *GImGui;
16208
0
    ImGuiStyle& style = g.Style;
16209
16210
0
    const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
16211
0
    const bool closed_all = node->WantCloseAll && node_was_active;
16212
0
    const ImGuiID closed_one = node->WantCloseTabId && node_was_active;
16213
0
    node->WantCloseAll = false;
16214
0
    node->WantCloseTabId = 0;
16215
16216
    // Decide if we should use a focused title bar color
16217
0
    bool is_focused = false;
16218
0
    ImGuiDockNode* root_node = DockNodeGetRootNode(node);
16219
0
    if (IsDockNodeTitleBarHighlighted(node, root_node))
16220
0
        is_focused = true;
16221
16222
    // Hidden tab bar will show a triangle on the upper-left (in Begin)
16223
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
16224
0
    {
16225
0
        node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
16226
0
        node->IsFocused = is_focused;
16227
0
        if (is_focused)
16228
0
            node->LastFrameFocused = g.FrameCount;
16229
0
        if (node->VisibleWindow)
16230
0
        {
16231
            // Notify root of visible window (used to display title in OS task bar)
16232
0
            if (is_focused || root_node->VisibleWindow == NULL)
16233
0
                root_node->VisibleWindow = node->VisibleWindow;
16234
0
            if (node->TabBar)
16235
0
                node->TabBar->VisibleTabId = node->VisibleWindow->TabId;
16236
0
        }
16237
0
        return;
16238
0
    }
16239
16240
    // Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
16241
0
    bool backup_skip_item = host_window->SkipItems;
16242
0
    if (!node->IsDockSpace())
16243
0
    {
16244
0
        host_window->SkipItems = false;
16245
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
16246
0
    }
16247
16248
    // Use PushOverrideID() instead of PushID() to use the node id _without_ the host window ID.
16249
    // This is to facilitate computing those ID from the outside, and will affect more or less only the ID of the collapse button, popup and tabs,
16250
    // as docked windows themselves will override the stack with their own root ID.
16251
0
    PushOverrideID(node->ID);
16252
0
    ImGuiTabBar* tab_bar = node->TabBar;
16253
0
    bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
16254
0
    if (tab_bar == NULL)
16255
0
    {
16256
0
        DockNodeAddTabBar(node);
16257
0
        tab_bar = node->TabBar;
16258
0
    }
16259
16260
0
    ImGuiID focus_tab_id = 0;
16261
0
    node->IsFocused = is_focused;
16262
16263
0
    const ImGuiDockNodeFlags node_flags = node->MergedFlags;
16264
0
    const bool has_window_menu_button = (node_flags & ImGuiDockNodeFlags_NoWindowMenuButton) == 0 && (style.WindowMenuButtonPosition != ImGuiDir_None);
16265
16266
    // In a dock node, the Collapse Button turns into the Window Menu button.
16267
    // FIXME-DOCK FIXME-OPT: Could we recycle popups id across multiple dock nodes?
16268
0
    if (has_window_menu_button && IsPopupOpen("#WindowMenu"))
16269
0
    {
16270
0
        if (ImGuiID tab_id = DockNodeUpdateWindowMenu(node, tab_bar))
16271
0
            focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
16272
0
        is_focused |= node->IsFocused;
16273
0
    }
16274
16275
    // Layout
16276
0
    ImRect title_bar_rect, tab_bar_rect;
16277
0
    ImVec2 window_menu_button_pos;
16278
0
    ImVec2 close_button_pos;
16279
0
    DockNodeCalcTabBarLayout(node, &title_bar_rect, &tab_bar_rect, &window_menu_button_pos, &close_button_pos);
16280
16281
    // Submit new tabs, they will be added as Unsorted and sorted below based on relative DockOrder value.
16282
0
    const int tabs_count_old = tab_bar->Tabs.Size;
16283
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16284
0
    {
16285
0
        ImGuiWindow* window = node->Windows[window_n];
16286
0
        if (TabBarFindTabByID(tab_bar, window->TabId) == NULL)
16287
0
            TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
16288
0
    }
16289
16290
    // Title bar
16291
0
    if (is_focused)
16292
0
        node->LastFrameFocused = g.FrameCount;
16293
0
    ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
16294
0
    ImDrawFlags rounding_flags = CalcRoundingFlagsForRectInRect(title_bar_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE);
16295
0
    host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, rounding_flags);
16296
16297
    // Docking/Collapse button
16298
0
    if (has_window_menu_button)
16299
0
    {
16300
0
        if (CollapseButton(host_window->GetID("#COLLAPSE"), window_menu_button_pos, node)) // == DockNodeGetWindowMenuButtonId(node)
16301
0
            OpenPopup("#WindowMenu");
16302
0
        if (IsItemActive())
16303
0
            focus_tab_id = tab_bar->SelectedTabId;
16304
0
    }
16305
16306
    // If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
16307
0
    int tabs_unsorted_start = tab_bar->Tabs.Size;
16308
0
    for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
16309
0
    {
16310
        // FIXME-DOCK: Consider only clearing the flag after the tab has been alive for a few consecutive frames, allowing late comers to not break sorting?
16311
0
        tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
16312
0
        tabs_unsorted_start = tab_n;
16313
0
    }
16314
0
    if (tab_bar->Tabs.Size > tabs_unsorted_start)
16315
0
    {
16316
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] In node 0x%08X: %d new appearing tabs:%s\n", node->ID, tab_bar->Tabs.Size - tabs_unsorted_start, (tab_bar->Tabs.Size > tabs_unsorted_start + 1) ? " (will sort)" : "");
16317
0
        for (int tab_n = tabs_unsorted_start; tab_n < tab_bar->Tabs.Size; tab_n++)
16318
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] - Tab '%s' Order %d\n", tab_bar->Tabs[tab_n].Window->Name, tab_bar->Tabs[tab_n].Window->DockOrder);
16319
0
        if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
16320
0
            ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
16321
0
    }
16322
16323
    // Apply NavWindow focus back to the tab bar
16324
0
    if (g.NavWindow && g.NavWindow->RootWindow->DockNode == node)
16325
0
        tab_bar->SelectedTabId = g.NavWindow->RootWindow->TabId;
16326
16327
    // Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
16328
0
    if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabId) != NULL)
16329
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabId;
16330
0
    else if (tab_bar->Tabs.Size > tabs_count_old)
16331
0
        tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->TabId;
16332
16333
    // Begin tab bar
16334
0
    ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
16335
0
    tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
16336
0
    if (!host_window->Collapsed && is_focused)
16337
0
        tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
16338
0
    BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
16339
    //host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
16340
16341
    // Backup style colors
16342
0
    ImVec4 backup_style_cols[ImGuiWindowDockStyleCol_COUNT];
16343
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16344
0
        backup_style_cols[color_n] = g.Style.Colors[GWindowDockStyleColors[color_n]];
16345
16346
    // Submit actual tabs
16347
0
    node->VisibleWindow = NULL;
16348
0
    for (int window_n = 0; window_n < node->Windows.Size; window_n++)
16349
0
    {
16350
0
        ImGuiWindow* window = node->Windows[window_n];
16351
0
        if ((closed_all || closed_one == window->TabId) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
16352
0
            continue;
16353
0
        if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
16354
0
        {
16355
0
            ImGuiTabItemFlags tab_item_flags = 0;
16356
0
            tab_item_flags |= window->WindowClass.TabItemFlagsOverrideSet;
16357
0
            if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
16358
0
                tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
16359
0
            if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
16360
0
                tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
16361
16362
            // Apply stored style overrides for the window
16363
0
            for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16364
0
                g.Style.Colors[GWindowDockStyleColors[color_n]] = ColorConvertU32ToFloat4(window->DockStyle.Colors[color_n]);
16365
16366
            // Note that TabItemEx() calls TabBarCalcTabID() so our tab item ID will ignore the current ID stack (rightly so)
16367
0
            bool tab_open = true;
16368
0
            TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
16369
0
            if (!tab_open)
16370
0
                node->WantCloseTabId = window->TabId;
16371
0
            if (tab_bar->VisibleTabId == window->TabId)
16372
0
                node->VisibleWindow = window;
16373
16374
            // Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
16375
0
            window->DockTabItemStatusFlags = g.LastItemData.StatusFlags;
16376
0
            window->DockTabItemRect = g.LastItemData.Rect;
16377
16378
            // Update navigation ID on menu layer
16379
0
            if (g.NavWindow && g.NavWindow->RootWindow == window && (window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 0)
16380
0
                host_window->NavLastIds[1] = window->TabId;
16381
0
        }
16382
0
    }
16383
16384
    // Restore style colors
16385
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
16386
0
        g.Style.Colors[GWindowDockStyleColors[color_n]] = backup_style_cols[color_n];
16387
16388
    // Notify root of visible window (used to display title in OS task bar)
16389
0
    if (node->VisibleWindow)
16390
0
        if (is_focused || root_node->VisibleWindow == NULL)
16391
0
            root_node->VisibleWindow = node->VisibleWindow;
16392
16393
    // Close button (after VisibleWindow was updated)
16394
    // Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->TabId may be != from tab_bar->SelectedTabId
16395
0
    const bool close_button_is_enabled = node->HasCloseButton && node->VisibleWindow && node->VisibleWindow->HasCloseButton;
16396
0
    const bool close_button_is_visible = node->HasCloseButton;
16397
    //const bool close_button_is_visible = close_button_is_enabled; // Most people would expect this behavior of not even showing the button (leaving a hole since we can't claim that space as other windows in the tba bar have one)
16398
0
    if (close_button_is_visible)
16399
0
    {
16400
0
        if (!close_button_is_enabled)
16401
0
        {
16402
0
            PushItemFlag(ImGuiItemFlags_Disabled, true);
16403
0
            PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.4f));
16404
0
        }
16405
0
        if (CloseButton(host_window->GetID("#CLOSE"), close_button_pos))
16406
0
        {
16407
0
            node->WantCloseAll = true;
16408
0
            for (int n = 0; n < tab_bar->Tabs.Size; n++)
16409
0
                TabBarCloseTab(tab_bar, &tab_bar->Tabs[n]);
16410
0
        }
16411
        //if (IsItemActive())
16412
        //    focus_tab_id = tab_bar->SelectedTabId;
16413
0
        if (!close_button_is_enabled)
16414
0
        {
16415
0
            PopStyleColor();
16416
0
            PopItemFlag();
16417
0
        }
16418
0
    }
16419
16420
    // When clicking on the title bar outside of tabs, we still focus the selected tab for that node
16421
    // FIXME: TabItem use AllowItemOverlap so we manually perform a more specific test for now (hovered || held)
16422
0
    ImGuiID title_bar_id = host_window->GetID("#TITLEBAR");
16423
0
    if (g.HoveredId == 0 || g.HoveredId == title_bar_id || g.ActiveId == title_bar_id)
16424
0
    {
16425
0
        bool held;
16426
0
        ButtonBehavior(title_bar_rect, title_bar_id, NULL, &held, ImGuiButtonFlags_AllowItemOverlap);
16427
0
        if (g.HoveredId == title_bar_id)
16428
0
        {
16429
            // ImGuiButtonFlags_AllowItemOverlap + SetItemAllowOverlap() required for appending into dock node tab bar,
16430
            // otherwise dragging window will steal HoveredId and amended tabs cannot get them.
16431
0
            g.LastItemData.ID = title_bar_id;
16432
0
            SetItemAllowOverlap();
16433
0
        }
16434
0
        if (held)
16435
0
        {
16436
0
            if (IsMouseClicked(0))
16437
0
                focus_tab_id = tab_bar->SelectedTabId;
16438
16439
            // Forward moving request to selected window
16440
0
            if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->SelectedTabId))
16441
0
                StartMouseMovingWindowOrNode(tab->Window ? tab->Window : node->HostWindow, node, false);
16442
0
        }
16443
0
    }
16444
16445
    // Forward focus from host node to selected window
16446
    //if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
16447
    //    focus_tab_id = tab_bar->SelectedTabId;
16448
16449
    // When clicked on a tab we requested focus to the docked child
16450
    // This overrides the value set by "forward focus from host node to selected window".
16451
0
    if (tab_bar->NextSelectedTabId)
16452
0
        focus_tab_id = tab_bar->NextSelectedTabId;
16453
16454
    // Apply navigation focus
16455
0
    if (focus_tab_id != 0)
16456
0
        if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
16457
0
            if (tab->Window)
16458
0
            {
16459
0
                FocusWindow(tab->Window);
16460
0
                NavInitWindow(tab->Window, false);
16461
0
            }
16462
16463
0
    EndTabBar();
16464
0
    PopID();
16465
16466
    // Restore SkipItems flag
16467
0
    if (!node->IsDockSpace())
16468
0
    {
16469
0
        host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
16470
0
        host_window->SkipItems = backup_skip_item;
16471
0
    }
16472
0
}
16473
16474
static void ImGui::DockNodeAddTabBar(ImGuiDockNode* node)
16475
0
{
16476
0
    IM_ASSERT(node->TabBar == NULL);
16477
0
    node->TabBar = IM_NEW(ImGuiTabBar);
16478
0
}
16479
16480
static void ImGui::DockNodeRemoveTabBar(ImGuiDockNode* node)
16481
0
{
16482
0
    if (node->TabBar == NULL)
16483
0
        return;
16484
0
    IM_DELETE(node->TabBar);
16485
0
    node->TabBar = NULL;
16486
0
}
16487
16488
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
16489
4
{
16490
4
    if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
16491
0
        return false;
16492
16493
4
    ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
16494
4
    ImGuiWindowClass* payload_class = &payload->WindowClass;
16495
4
    if (host_class->ClassId != payload_class->ClassId)
16496
0
    {
16497
0
        if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
16498
0
            return true;
16499
0
        if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
16500
0
            return true;
16501
0
        return false;
16502
0
    }
16503
16504
    // Prevent docking any window created above a popup
16505
    // Technically we should support it (e.g. in the case of a long-lived modal window that had fancy docking features),
16506
    // by e.g. adding a 'if (!ImGui::IsWindowWithinBeginStackOf(host_window, popup_window))' test.
16507
    // But it would requires more work on our end because the dock host windows is technically created in NewFrame()
16508
    // and our ->ParentXXX and ->RootXXX pointers inside windows are currently mislading or lacking.
16509
4
    ImGuiContext& g = *GImGui;
16510
4
    for (int i = g.OpenPopupStack.Size - 1; i >= 0; i--)
16511
0
        if (ImGuiWindow* popup_window = g.OpenPopupStack[i].Window)
16512
0
            if (ImGui::IsWindowWithinBeginStackOf(payload, popup_window))   // Payload is created from within a popup begin stack.
16513
0
                return false;
16514
16515
4
    return true;
16516
4
}
16517
16518
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
16519
4
{
16520
4
    if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode()) // FIXME-DOCK: Missing filtering
16521
0
        return true;
16522
16523
4
    const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
16524
4
    for (int payload_n = 0; payload_n < payload_count; payload_n++)
16525
4
    {
16526
4
        ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
16527
4
        if (DockNodeIsDropAllowedOne(payload, host_window))
16528
4
            return true;
16529
4
    }
16530
0
    return false;
16531
4
}
16532
16533
// window menu button == collapse button when not in a dock node.
16534
// FIXME: This is similar to RenderWindowTitleBarContents(), may want to share code.
16535
static void ImGui::DockNodeCalcTabBarLayout(const ImGuiDockNode* node, ImRect* out_title_rect, ImRect* out_tab_bar_rect, ImVec2* out_window_menu_button_pos, ImVec2* out_close_button_pos)
16536
0
{
16537
0
    ImGuiContext& g = *GImGui;
16538
0
    ImGuiStyle& style = g.Style;
16539
16540
0
    ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + g.FontSize + g.Style.FramePadding.y * 2.0f);
16541
0
    if (out_title_rect) { *out_title_rect = r; }
16542
16543
0
    r.Min.x += style.WindowBorderSize;
16544
0
    r.Max.x -= style.WindowBorderSize;
16545
16546
0
    float button_sz = g.FontSize;
16547
16548
0
    ImVec2 window_menu_button_pos = r.Min;
16549
0
    r.Min.x += style.FramePadding.x;
16550
0
    r.Max.x -= style.FramePadding.x;
16551
0
    if (node->HasCloseButton)
16552
0
    {
16553
0
        r.Max.x -= button_sz;
16554
0
        if (out_close_button_pos) *out_close_button_pos = ImVec2(r.Max.x - style.FramePadding.x, r.Min.y);
16555
0
    }
16556
0
    if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Left)
16557
0
    {
16558
0
        r.Min.x += button_sz + style.ItemInnerSpacing.x;
16559
0
    }
16560
0
    else if (node->HasWindowMenuButton && style.WindowMenuButtonPosition == ImGuiDir_Right)
16561
0
    {
16562
0
        r.Max.x -= button_sz + style.FramePadding.x;
16563
0
        window_menu_button_pos = ImVec2(r.Max.x, r.Min.y);
16564
0
    }
16565
0
    if (out_tab_bar_rect) { *out_tab_bar_rect = r; }
16566
0
    if (out_window_menu_button_pos) { *out_window_menu_button_pos = window_menu_button_pos; }
16567
0
}
16568
16569
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
16570
0
{
16571
0
    ImGuiContext& g = *GImGui;
16572
0
    const float dock_spacing = g.Style.ItemInnerSpacing.x;
16573
0
    const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16574
0
    pos_new[axis ^ 1] = pos_old[axis ^ 1];
16575
0
    size_new[axis ^ 1] = size_old[axis ^ 1];
16576
16577
    // Distribute size on given axis (with a desired size or equally)
16578
0
    const float w_avail = size_old[axis] - dock_spacing;
16579
0
    if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
16580
0
    {
16581
0
        size_new[axis] = size_new_desired[axis];
16582
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16583
0
    }
16584
0
    else
16585
0
    {
16586
0
        size_new[axis] = IM_FLOOR(w_avail * 0.5f);
16587
0
        size_old[axis] = IM_FLOOR(w_avail - size_new[axis]);
16588
0
    }
16589
16590
    // Position each node
16591
0
    if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
16592
0
    {
16593
0
        pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
16594
0
    }
16595
0
    else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
16596
0
    {
16597
0
        pos_new[axis] = pos_old[axis];
16598
0
        pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
16599
0
    }
16600
0
}
16601
16602
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
16603
bool ImGui::DockNodeCalcDropRectsAndTestMousePos(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking, ImVec2* test_mouse_pos)
16604
0
{
16605
0
    ImGuiContext& g = *GImGui;
16606
16607
0
    const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
16608
0
    const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
16609
0
    float hs_w; // Half-size, longer axis
16610
0
    float hs_h; // Half-size, smaller axis
16611
0
    ImVec2 off; // Distance from edge or center
16612
0
    if (outer_docking)
16613
0
    {
16614
        //hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
16615
        //hs_h = ImFloor(hs_w * 0.15f);
16616
        //off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
16617
0
        hs_w = ImFloor(hs_for_central_nodes * 1.50f);
16618
0
        hs_h = ImFloor(hs_for_central_nodes * 0.80f);
16619
0
        off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - hs_h), ImFloor(parent.GetHeight() * 0.5f - hs_h));
16620
0
    }
16621
0
    else
16622
0
    {
16623
0
        hs_w = ImFloor(hs_for_central_nodes);
16624
0
        hs_h = ImFloor(hs_for_central_nodes * 0.90f);
16625
0
        off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
16626
0
    }
16627
16628
0
    ImVec2 c = ImFloor(parent.GetCenter());
16629
0
    if      (dir == ImGuiDir_None)  { out_r = ImRect(c.x - hs_w, c.y - hs_w,         c.x + hs_w, c.y + hs_w);         }
16630
0
    else if (dir == ImGuiDir_Up)    { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
16631
0
    else if (dir == ImGuiDir_Down)  { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
16632
0
    else if (dir == ImGuiDir_Left)  { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
16633
0
    else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
16634
16635
0
    if (test_mouse_pos == NULL)
16636
0
        return false;
16637
16638
0
    ImRect hit_r = out_r;
16639
0
    if (!outer_docking)
16640
0
    {
16641
        // Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
16642
0
        hit_r.Expand(ImFloor(hs_w * 0.30f));
16643
0
        ImVec2 mouse_delta = (*test_mouse_pos - c);
16644
0
        float mouse_delta_len2 = ImLengthSqr(mouse_delta);
16645
0
        float r_threshold_center = hs_w * 1.4f;
16646
0
        float r_threshold_sides = hs_w * (1.4f + 1.2f);
16647
0
        if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
16648
0
            return (dir == ImGuiDir_None);
16649
0
        if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
16650
0
            return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
16651
0
    }
16652
0
    return hit_r.Contains(*test_mouse_pos);
16653
0
}
16654
16655
// host_node may be NULL if the window doesn't have a DockNode already.
16656
// FIXME-DOCK: This is misnamed since it's also doing the filtering.
16657
static void ImGui::DockNodePreviewDockSetup(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockNode* payload_node, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
16658
0
{
16659
0
    ImGuiContext& g = *GImGui;
16660
16661
    // There is an edge case when docking into a dockspace which only has inactive nodes.
16662
    // In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
16663
    // Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
16664
0
    if (payload_node == NULL)
16665
0
        payload_node = payload_window->DockNodeAsHost;
16666
0
    ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
16667
0
    if (ref_node_for_rect)
16668
0
        IM_ASSERT(ref_node_for_rect->IsVisible == true);
16669
16670
    // Filter, figure out where we are allowed to dock
16671
0
    ImGuiDockNodeFlags src_node_flags = payload_node ? payload_node->MergedFlags : payload_window->WindowClass.DockNodeFlagsOverrideSet;
16672
0
    ImGuiDockNodeFlags dst_node_flags = host_node ? host_node->MergedFlags : host_window->WindowClass.DockNodeFlagsOverrideSet;
16673
0
    data->IsCenterAvailable = true;
16674
0
    if (is_outer_docking)
16675
0
        data->IsCenterAvailable = false;
16676
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDocking)
16677
0
        data->IsCenterAvailable = false;
16678
0
    else if (host_node && (dst_node_flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode())
16679
0
        data->IsCenterAvailable = false;
16680
0
    else if ((!host_node || !host_node->IsEmpty()) && payload_node && payload_node->IsSplitNode() && (payload_node->OnlyNodeWithWindows == NULL)) // Is _visibly_ split?
16681
0
        data->IsCenterAvailable = false;
16682
0
    else if (dst_node_flags & ImGuiDockNodeFlags_NoDockingOverMe)
16683
0
        data->IsCenterAvailable = false;
16684
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverOther) && (!host_node || !host_node->IsEmpty()))
16685
0
        data->IsCenterAvailable = false;
16686
0
    else if ((src_node_flags & ImGuiDockNodeFlags_NoDockingOverEmpty) && host_node && host_node->IsEmpty())
16687
0
        data->IsCenterAvailable = false;
16688
16689
0
    data->IsSidesAvailable = true;
16690
0
    if ((dst_node_flags & ImGuiDockNodeFlags_NoSplit) || g.IO.ConfigDockingNoSplit)
16691
0
        data->IsSidesAvailable = false;
16692
0
    else if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode())
16693
0
        data->IsSidesAvailable = false;
16694
0
    else if ((dst_node_flags & ImGuiDockNodeFlags_NoDockingSplitMe) || (src_node_flags & ImGuiDockNodeFlags_NoDockingSplitOther))
16695
0
        data->IsSidesAvailable = false;
16696
16697
    // Build a tentative future node (reuse same structure because it is practical. Shape will be readjusted when previewing a split)
16698
0
    data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (payload_window->HasCloseButton);
16699
0
    data->FutureNode.HasWindowMenuButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
16700
0
    data->FutureNode.Pos = ref_node_for_rect ? ref_node_for_rect->Pos : host_window->Pos;
16701
0
    data->FutureNode.Size = ref_node_for_rect ? ref_node_for_rect->Size : host_window->Size;
16702
16703
    // Calculate drop shapes geometry for allowed splitting directions
16704
0
    IM_ASSERT(ImGuiDir_None == -1);
16705
0
    data->SplitNode = host_node;
16706
0
    data->SplitDir = ImGuiDir_None;
16707
0
    data->IsSplitDirExplicit = false;
16708
0
    if (!host_window->Collapsed)
16709
0
        for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16710
0
        {
16711
0
            if (dir == ImGuiDir_None && !data->IsCenterAvailable)
16712
0
                continue;
16713
0
            if (dir != ImGuiDir_None && !data->IsSidesAvailable)
16714
0
                continue;
16715
0
            if (DockNodeCalcDropRectsAndTestMousePos(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking, &g.IO.MousePos))
16716
0
            {
16717
0
                data->SplitDir = (ImGuiDir)dir;
16718
0
                data->IsSplitDirExplicit = true;
16719
0
            }
16720
0
        }
16721
16722
    // When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
16723
0
    data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
16724
0
    if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
16725
0
        data->IsDropAllowed = false;
16726
16727
    // Calculate split area
16728
0
    data->SplitRatio = 0.0f;
16729
0
    if (data->SplitDir != ImGuiDir_None)
16730
0
    {
16731
0
        ImGuiDir split_dir = data->SplitDir;
16732
0
        ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
16733
0
        ImVec2 pos_new, pos_old = data->FutureNode.Pos;
16734
0
        ImVec2 size_new, size_old = data->FutureNode.Size;
16735
0
        DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, payload_window->Size);
16736
16737
        // Calculate split ratio so we can pass it down the docking request
16738
0
        float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
16739
0
        data->FutureNode.Pos = pos_new;
16740
0
        data->FutureNode.Size = size_new;
16741
0
        data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
16742
0
    }
16743
0
}
16744
16745
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
16746
0
{
16747
0
    ImGuiContext& g = *GImGui;
16748
0
    IM_ASSERT(g.CurrentWindow == host_window);   // Because we rely on font size to calculate tab sizes
16749
16750
    // With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
16751
    // To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
16752
0
    const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
16753
16754
    // In case the two windows involved are on different viewports, we will draw the overlay on each of them.
16755
0
    int overlay_draw_lists_count = 0;
16756
0
    ImDrawList* overlay_draw_lists[2];
16757
0
    overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(host_window->Viewport);
16758
0
    if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
16759
0
        overlay_draw_lists[overlay_draw_lists_count++] = GetForegroundDrawList(root_payload->Viewport);
16760
16761
    // Draw main preview rectangle
16762
0
    const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
16763
0
    const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
16764
0
    const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
16765
0
    const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
16766
16767
    // Display area preview
16768
0
    const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
16769
0
    if (data->IsDropAllowed)
16770
0
    {
16771
0
        ImRect overlay_rect = data->FutureNode.Rect();
16772
0
        if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
16773
0
            overlay_rect.Min.y += GetFrameHeight();
16774
0
        if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
16775
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16776
0
                overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding, CalcRoundingFlagsForRectInRect(overlay_rect, host_window->Rect(), DOCKING_SPLITTER_SIZE));
16777
0
    }
16778
16779
    // Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
16780
0
    if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
16781
0
    {
16782
        // Compute target tab bar geometry so we can locate our preview tabs
16783
0
        ImRect tab_bar_rect;
16784
0
        DockNodeCalcTabBarLayout(&data->FutureNode, NULL, &tab_bar_rect, NULL, NULL);
16785
0
        ImVec2 tab_pos = tab_bar_rect.Min;
16786
0
        if (host_node && host_node->TabBar)
16787
0
        {
16788
0
            if (!host_node->IsHiddenTabBar() && !host_node->IsNoTabBar())
16789
0
                tab_pos.x += host_node->TabBar->WidthAllTabs + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
16790
0
            else
16791
0
                tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]).x;
16792
0
        }
16793
0
        else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
16794
0
        {
16795
0
            tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window).x; // Account for slight offset which will be added when changing from title bar to tab bar
16796
0
        }
16797
16798
        // Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
16799
0
        if (root_payload->DockNodeAsHost)
16800
0
            IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size <= root_payload->DockNodeAsHost->TabBar->Tabs.Size);
16801
0
        ImGuiTabBar* tab_bar_with_payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar : NULL;
16802
0
        const int payload_count = tab_bar_with_payload ? tab_bar_with_payload->Tabs.Size : 1;
16803
0
        for (int payload_n = 0; payload_n < payload_count; payload_n++)
16804
0
        {
16805
            // DockNode's TabBar may have non-window Tabs manually appended by user
16806
0
            ImGuiWindow* payload_window = tab_bar_with_payload ? tab_bar_with_payload->Tabs[payload_n].Window : root_payload;
16807
0
            if (tab_bar_with_payload && payload_window == NULL)
16808
0
                continue;
16809
0
            if (!DockNodeIsDropAllowedOne(payload_window, host_window))
16810
0
                continue;
16811
16812
            // Calculate the tab bounding box for each payload window
16813
0
            ImVec2 tab_size = TabItemCalcSize(payload_window);
16814
0
            ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
16815
0
            tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
16816
0
            const ImU32 overlay_col_text = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_Text]);
16817
0
            const ImU32 overlay_col_tabs = GetColorU32(payload_window->DockStyle.Colors[ImGuiWindowDockStyleCol_TabActive]);
16818
0
            PushStyleColor(ImGuiCol_Text, overlay_col_text);
16819
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16820
0
            {
16821
0
                ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload_window->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
16822
0
                if (!tab_bar_rect.Contains(tab_bb))
16823
0
                    overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
16824
0
                TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
16825
0
                TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload_window->Name, 0, 0, false, NULL, NULL);
16826
0
                if (!tab_bar_rect.Contains(tab_bb))
16827
0
                    overlay_draw_lists[overlay_n]->PopClipRect();
16828
0
            }
16829
0
            PopStyleColor();
16830
0
        }
16831
0
    }
16832
16833
    // Display drop boxes
16834
0
    const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
16835
0
    for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
16836
0
    {
16837
0
        if (!data->DropRectsDraw[dir + 1].IsInverted())
16838
0
        {
16839
0
            ImRect draw_r = data->DropRectsDraw[dir + 1];
16840
0
            ImRect draw_r_in = draw_r;
16841
0
            draw_r_in.Expand(-2.0f);
16842
0
            ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
16843
0
            for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
16844
0
            {
16845
0
                ImVec2 center = ImFloor(draw_r_in.GetCenter());
16846
0
                overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
16847
0
                overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
16848
0
                if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
16849
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
16850
0
                if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
16851
0
                    overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
16852
0
            }
16853
0
        }
16854
16855
        // Stop after ImGuiDir_None
16856
0
        if ((host_node && (host_node->MergedFlags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
16857
0
            return;
16858
0
    }
16859
0
}
16860
16861
//-----------------------------------------------------------------------------
16862
// Docking: ImGuiDockNode Tree manipulation functions
16863
//-----------------------------------------------------------------------------
16864
// - DockNodeTreeSplit()
16865
// - DockNodeTreeMerge()
16866
// - DockNodeTreeUpdatePosSize()
16867
// - DockNodeTreeUpdateSplitterFindTouchingNode()
16868
// - DockNodeTreeUpdateSplitter()
16869
// - DockNodeTreeFindFallbackLeafNode()
16870
// - DockNodeTreeFindNodeByPos()
16871
//-----------------------------------------------------------------------------
16872
16873
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
16874
0
{
16875
0
    ImGuiContext& g = *GImGui;
16876
0
    IM_ASSERT(split_axis != ImGuiAxis_None);
16877
16878
0
    ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
16879
0
    child_0->ParentNode = parent_node;
16880
16881
0
    ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
16882
0
    child_1->ParentNode = parent_node;
16883
16884
0
    ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
16885
0
    DockNodeMoveChildNodes(child_inheritor, parent_node);
16886
0
    parent_node->ChildNodes[0] = child_0;
16887
0
    parent_node->ChildNodes[1] = child_1;
16888
0
    parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
16889
0
    parent_node->SplitAxis = split_axis;
16890
0
    parent_node->VisibleWindow = NULL;
16891
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = ImGuiDataAuthority_DockNode;
16892
16893
0
    float size_avail = (parent_node->Size[split_axis] - DOCKING_SPLITTER_SIZE);
16894
0
    size_avail = ImMax(size_avail, g.Style.WindowMinSize[split_axis] * 2.0f);
16895
0
    IM_ASSERT(size_avail > 0.0f); // If you created a node manually with DockBuilderAddNode(), you need to also call DockBuilderSetNodeSize() before splitting.
16896
0
    child_0->SizeRef = child_1->SizeRef = parent_node->Size;
16897
0
    child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
16898
0
    child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
16899
16900
0
    DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
16901
0
    DockSettingsRenameNodeReferences(parent_node->ID, parent_node->ChildNodes[split_inheritor_child_idx]->ID);
16902
0
    DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(parent_node));
16903
0
    DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
16904
16905
    // Flags transfer (e.g. this is where we transfer the ImGuiDockNodeFlags_CentralNode property)
16906
0
    child_0->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16907
0
    child_1->SharedFlags = parent_node->SharedFlags & ImGuiDockNodeFlags_SharedFlagsInheritMask_;
16908
0
    child_inheritor->LocalFlags = parent_node->LocalFlags & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16909
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16910
0
    child_0->UpdateMergedFlags();
16911
0
    child_1->UpdateMergedFlags();
16912
0
    parent_node->UpdateMergedFlags();
16913
0
    if (child_inheritor->IsCentralNode())
16914
0
        DockNodeGetRootNode(parent_node)->CentralNode = child_inheritor;
16915
0
}
16916
16917
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
16918
0
{
16919
    // When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
16920
0
    ImGuiContext& g = *GImGui;
16921
0
    ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
16922
0
    ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
16923
0
    IM_ASSERT(child_0 || child_1);
16924
0
    IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
16925
0
    if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
16926
0
    {
16927
0
        IM_ASSERT(parent_node->TabBar == NULL);
16928
0
        IM_ASSERT(parent_node->Windows.Size == 0);
16929
0
    }
16930
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockNodeTreeMerge: 0x%08X + 0x%08X back into parent 0x%08X\n", child_0 ? child_0->ID : 0, child_1 ? child_1->ID : 0, parent_node->ID);
16931
16932
0
    ImVec2 backup_last_explicit_size = parent_node->SizeRef;
16933
0
    DockNodeMoveChildNodes(parent_node, merge_lead_child);
16934
0
    if (child_0)
16935
0
    {
16936
0
        DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
16937
0
        DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
16938
0
    }
16939
0
    if (child_1)
16940
0
    {
16941
0
        DockNodeMoveWindows(parent_node, child_1);
16942
0
        DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
16943
0
    }
16944
0
    DockNodeApplyPosSizeToWindows(parent_node);
16945
0
    parent_node->AuthorityForPos = parent_node->AuthorityForSize = parent_node->AuthorityForViewport = ImGuiDataAuthority_Auto;
16946
0
    parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
16947
0
    parent_node->SizeRef = backup_last_explicit_size;
16948
16949
    // Flags transfer
16950
0
    parent_node->LocalFlags &= ~ImGuiDockNodeFlags_LocalFlagsTransferMask_; // Preserve Dockspace flag
16951
0
    parent_node->LocalFlags |= (child_0 ? child_0->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16952
0
    parent_node->LocalFlags |= (child_1 ? child_1->LocalFlags : 0) & ImGuiDockNodeFlags_LocalFlagsTransferMask_;
16953
0
    parent_node->LocalFlagsInWindows = (child_0 ? child_0->LocalFlagsInWindows : 0) | (child_1 ? child_1->LocalFlagsInWindows : 0); // FIXME: Would be more consistent to update from actual windows
16954
0
    parent_node->UpdateMergedFlags();
16955
16956
0
    if (child_0)
16957
0
    {
16958
0
        ctx->DockContext.Nodes.SetVoidPtr(child_0->ID, NULL);
16959
0
        IM_DELETE(child_0);
16960
0
    }
16961
0
    if (child_1)
16962
0
    {
16963
0
        ctx->DockContext.Nodes.SetVoidPtr(child_1->ID, NULL);
16964
0
        IM_DELETE(child_1);
16965
0
    }
16966
0
}
16967
16968
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
16969
// (Depth-first, Pre-Order)
16970
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size, ImGuiDockNode* only_write_to_single_node)
16971
0
{
16972
    // During the regular dock node update we write to all nodes.
16973
    // 'only_write_to_single_node' is only set when turning a node visible mid-frame and we need its size right-away.
16974
0
    const bool write_to_node = only_write_to_single_node == NULL || only_write_to_single_node == node;
16975
0
    if (write_to_node)
16976
0
    {
16977
0
        node->Pos = pos;
16978
0
        node->Size = size;
16979
0
    }
16980
16981
0
    if (node->IsLeafNode())
16982
0
        return;
16983
16984
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
16985
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
16986
0
    ImVec2 child_0_pos = pos, child_1_pos = pos;
16987
0
    ImVec2 child_0_size = size, child_1_size = size;
16988
16989
0
    const bool child_0_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_0));
16990
0
    const bool child_1_is_toward_single_node = (only_write_to_single_node != NULL && DockNodeIsInHierarchyOf(only_write_to_single_node, child_1));
16991
0
    const bool child_0_is_or_will_be_visible = child_0->IsVisible || child_0_is_toward_single_node;
16992
0
    const bool child_1_is_or_will_be_visible = child_1->IsVisible || child_1_is_toward_single_node;
16993
16994
0
    if (child_0_is_or_will_be_visible && child_1_is_or_will_be_visible)
16995
0
    {
16996
0
        ImGuiContext& g = *GImGui;
16997
0
        const float spacing = DOCKING_SPLITTER_SIZE;
16998
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
16999
0
        const float size_avail = ImMax(size[axis] - spacing, 0.0f);
17000
17001
        // Size allocation policy
17002
        // 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
17003
0
        const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
17004
17005
        // FIXME: Blocks 2) and 3) are essentially doing nearly the same thing.
17006
        // Difference are: write-back to SizeRef; application of a minimum size; rounding before ImFloor()
17007
        // Clarify and rework differences between Size & SizeRef and purpose of WantLockSizeOnce
17008
17009
        // 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
17010
0
        if (child_0->WantLockSizeOnce && !child_1->WantLockSizeOnce)
17011
0
        {
17012
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImMin(size_avail - 1.0f, child_0->Size[axis]);
17013
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17014
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17015
0
        }
17016
0
        else if (child_1->WantLockSizeOnce && !child_0->WantLockSizeOnce)
17017
0
        {
17018
0
            child_1_size[axis] = child_1->SizeRef[axis] = ImMin(size_avail - 1.0f, child_1->Size[axis]);
17019
0
            child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
17020
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17021
0
        }
17022
0
        else if (child_0->WantLockSizeOnce && child_1->WantLockSizeOnce)
17023
0
        {
17024
            // FIXME-DOCK: We cannot honor the requested size, so apply ratio.
17025
            // Currently this path will only be taken if code programmatically sets WantLockSizeOnce
17026
0
            float split_ratio = child_0_size[axis] / (child_0_size[axis] + child_1_size[axis]);
17027
0
            child_0_size[axis] = child_0->SizeRef[axis] = ImFloor(size_avail * split_ratio);
17028
0
            child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
17029
0
            IM_ASSERT(child_0->SizeRef[axis] > 0.0f && child_1->SizeRef[axis] > 0.0f);
17030
0
        }
17031
17032
        // 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
17033
0
        else if (child_0->SizeRef[axis] != 0.0f && child_1->HasCentralNodeChild)
17034
0
        {
17035
0
            child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
17036
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17037
0
        }
17038
0
        else if (child_1->SizeRef[axis] != 0.0f && child_0->HasCentralNodeChild)
17039
0
        {
17040
0
            child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
17041
0
            child_0_size[axis] = (size_avail - child_1_size[axis]);
17042
0
        }
17043
0
        else
17044
0
        {
17045
            // 4) Otherwise distribute according to the relative ratio of each SizeRef value
17046
0
            float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
17047
0
            child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5f));
17048
0
            child_1_size[axis] = (size_avail - child_0_size[axis]);
17049
0
        }
17050
17051
0
        child_1_pos[axis] += spacing + child_0_size[axis];
17052
0
    }
17053
17054
0
    if (only_write_to_single_node == NULL)
17055
0
        child_0->WantLockSizeOnce = child_1->WantLockSizeOnce = false;
17056
17057
0
    const bool child_0_recurse = only_write_to_single_node ? child_0_is_toward_single_node : child_0->IsVisible;
17058
0
    const bool child_1_recurse = only_write_to_single_node ? child_1_is_toward_single_node : child_1->IsVisible;
17059
0
    if (child_0_recurse)
17060
0
        DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
17061
0
    if (child_1_recurse)
17062
0
        DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
17063
0
}
17064
17065
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
17066
0
{
17067
0
    if (node->IsLeafNode())
17068
0
    {
17069
0
        touching_nodes->push_back(node);
17070
0
        return;
17071
0
    }
17072
0
    if (node->ChildNodes[0]->IsVisible)
17073
0
        if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
17074
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
17075
0
    if (node->ChildNodes[1]->IsVisible)
17076
0
        if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
17077
0
            DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
17078
0
}
17079
17080
// (Depth-First, Pre-Order)
17081
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
17082
0
{
17083
0
    if (node->IsLeafNode())
17084
0
        return;
17085
17086
0
    ImGuiContext& g = *GImGui;
17087
17088
0
    ImGuiDockNode* child_0 = node->ChildNodes[0];
17089
0
    ImGuiDockNode* child_1 = node->ChildNodes[1];
17090
0
    if (child_0->IsVisible && child_1->IsVisible)
17091
0
    {
17092
        // Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
17093
0
        const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
17094
0
        IM_ASSERT(axis != ImGuiAxis_None);
17095
0
        ImRect bb;
17096
0
        bb.Min = child_0->Pos;
17097
0
        bb.Max = child_1->Pos;
17098
0
        bb.Min[axis] += child_0->Size[axis];
17099
0
        bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
17100
        //if (g.IO.KeyCtrl) GetForegroundDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
17101
17102
0
        const ImGuiDockNodeFlags merged_flags = child_0->MergedFlags | child_1->MergedFlags; // Merged flags for BOTH childs
17103
0
        const ImGuiDockNodeFlags no_resize_axis_flag = (axis == ImGuiAxis_X) ? ImGuiDockNodeFlags_NoResizeX : ImGuiDockNodeFlags_NoResizeY;
17104
0
        if ((merged_flags & ImGuiDockNodeFlags_NoResize) || (merged_flags & no_resize_axis_flag))
17105
0
        {
17106
0
            ImGuiWindow* window = g.CurrentWindow;
17107
0
            window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
17108
0
        }
17109
0
        else
17110
0
        {
17111
            //bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
17112
            //bb.Max[axis] -= 1;
17113
0
            PushID(node->ID);
17114
17115
            // Find resizing limits by gathering list of nodes that are touching the splitter line.
17116
0
            ImVector<ImGuiDockNode*> touching_nodes[2];
17117
0
            float min_size = g.Style.WindowMinSize[axis];
17118
0
            float resize_limits[2];
17119
0
            resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
17120
0
            resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
17121
17122
0
            ImGuiID splitter_id = GetID("##Splitter");
17123
0
            if (g.ActiveId == splitter_id) // Only process when splitter is active
17124
0
            {
17125
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
17126
0
                DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
17127
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
17128
0
                    resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
17129
0
                for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
17130
0
                    resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
17131
17132
                // [DEBUG] Render touching nodes & limits
17133
                /*
17134
                ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17135
                for (int n = 0; n < 2; n++)
17136
                {
17137
                    for (int touching_node_n = 0; touching_node_n < touching_nodes[n].Size; touching_node_n++)
17138
                        draw_list->AddRect(touching_nodes[n][touching_node_n]->Pos, touching_nodes[n][touching_node_n]->Pos + touching_nodes[n][touching_node_n]->Size, IM_COL32(0, 255, 0, 255));
17139
                    if (axis == ImGuiAxis_X)
17140
                        draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
17141
                    else
17142
                        draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
17143
                }
17144
                */
17145
0
            }
17146
17147
            // Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
17148
0
            float cur_size_0 = child_0->Size[axis];
17149
0
            float cur_size_1 = child_1->Size[axis];
17150
0
            float min_size_0 = resize_limits[0] - child_0->Pos[axis];
17151
0
            float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
17152
0
            ImU32 bg_col = GetColorU32(ImGuiCol_WindowBg);
17153
0
            if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_HOVER_PADDING, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER, bg_col))
17154
0
            {
17155
0
                if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
17156
0
                {
17157
0
                    child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
17158
0
                    child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
17159
0
                    child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
17160
17161
                    // Lock the size of every node that is a sibling of the node we are touching
17162
                    // This might be less desirable if we can merge sibling of a same axis into the same parental level.
17163
0
                    for (int side_n = 0; side_n < 2; side_n++)
17164
0
                        for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
17165
0
                        {
17166
0
                            ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
17167
                            //ImDrawList* draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
17168
                            //draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
17169
0
                            while (touching_node->ParentNode != node)
17170
0
                            {
17171
0
                                if (touching_node->ParentNode->SplitAxis == axis)
17172
0
                                {
17173
                                    // Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
17174
0
                                    ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
17175
0
                                    node_to_preserve->WantLockSizeOnce = true;
17176
                                    //draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
17177
                                    //draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
17178
0
                                }
17179
0
                                touching_node = touching_node->ParentNode;
17180
0
                            }
17181
0
                        }
17182
17183
0
                    DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
17184
0
                    DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
17185
0
                    MarkIniSettingsDirty();
17186
0
                }
17187
0
            }
17188
0
            PopID();
17189
0
        }
17190
0
    }
17191
17192
0
    if (child_0->IsVisible)
17193
0
        DockNodeTreeUpdateSplitter(child_0);
17194
0
    if (child_1->IsVisible)
17195
0
        DockNodeTreeUpdateSplitter(child_1);
17196
0
}
17197
17198
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
17199
0
{
17200
0
    if (node->IsLeafNode())
17201
0
        return node;
17202
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
17203
0
        return leaf_node;
17204
0
    if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
17205
0
        return leaf_node;
17206
0
    return NULL;
17207
0
}
17208
17209
ImGuiDockNode* ImGui::DockNodeTreeFindVisibleNodeByPos(ImGuiDockNode* node, ImVec2 pos)
17210
0
{
17211
0
    if (!node->IsVisible)
17212
0
        return NULL;
17213
17214
0
    const float dock_spacing = 0.0f;// g.Style.ItemInnerSpacing.x; // FIXME: Relation to DOCKING_SPLITTER_SIZE?
17215
0
    ImRect r(node->Pos, node->Pos + node->Size);
17216
0
    r.Expand(dock_spacing * 0.5f);
17217
0
    bool inside = r.Contains(pos);
17218
0
    if (!inside)
17219
0
        return NULL;
17220
17221
0
    if (node->IsLeafNode())
17222
0
        return node;
17223
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[0], pos))
17224
0
        return hovered_node;
17225
0
    if (ImGuiDockNode* hovered_node = DockNodeTreeFindVisibleNodeByPos(node->ChildNodes[1], pos))
17226
0
        return hovered_node;
17227
17228
    // This means we are hovering over the splitter/spacing of a parent node
17229
0
    return node;
17230
0
}
17231
17232
//-----------------------------------------------------------------------------
17233
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
17234
//-----------------------------------------------------------------------------
17235
// - SetWindowDock() [Internal]
17236
// - DockSpace()
17237
// - DockSpaceOverViewport()
17238
//-----------------------------------------------------------------------------
17239
17240
// [Internal] Called via SetNextWindowDockID()
17241
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
17242
0
{
17243
    // Test condition (NB: bit 0 is always true) and clear flags for next time
17244
0
    if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
17245
0
        return;
17246
0
    window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
17247
17248
0
    if (window->DockId == dock_id)
17249
0
        return;
17250
17251
    // If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
17252
0
    ImGuiContext* ctx = GImGui;
17253
0
    if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
17254
0
        if (new_node->IsSplitNode())
17255
0
        {
17256
            // Policy: Find central node or latest focused node. We first move back to our root node.
17257
0
            new_node = DockNodeGetRootNode(new_node);
17258
0
            if (new_node->CentralNode)
17259
0
            {
17260
0
                IM_ASSERT(new_node->CentralNode->IsCentralNode());
17261
0
                dock_id = new_node->CentralNode->ID;
17262
0
            }
17263
0
            else
17264
0
            {
17265
0
                dock_id = new_node->LastFocusedNodeId;
17266
0
            }
17267
0
        }
17268
17269
0
    if (window->DockId == dock_id)
17270
0
        return;
17271
17272
0
    if (window->DockNode)
17273
0
        DockNodeRemoveWindow(window->DockNode, window, 0);
17274
0
    window->DockId = dock_id;
17275
0
}
17276
17277
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
17278
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
17279
// DockSpace() needs to be submitted _before_ any window they can host. If you use a dockspace, submit it early in your app.
17280
// When ImGuiDockNodeFlags_KeepAliveOnly is set, nothing is submitted in the current window (function may be called from any location).
17281
ImGuiID ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags flags, const ImGuiWindowClass* window_class)
17282
0
{
17283
0
    ImGuiContext* ctx = GImGui;
17284
0
    ImGuiContext& g = *ctx;
17285
0
    ImGuiWindow* window = GetCurrentWindowRead();
17286
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
17287
0
        return 0;
17288
17289
    // Early out if parent window is hidden/collapsed
17290
    // This is faster but also DockNodeUpdateTabBar() relies on TabBarLayout() running (which won't if SkipItems=true) to set NextSelectedTabId = 0). See #2960.
17291
    // If for whichever reason this is causing problem we would need to ensure that DockNodeUpdateTabBar() ends up clearing NextSelectedTabId even if SkipItems=true.
17292
0
    if (window->SkipItems)
17293
0
        flags |= ImGuiDockNodeFlags_KeepAliveOnly;
17294
0
    if ((flags & ImGuiDockNodeFlags_KeepAliveOnly) == 0)
17295
0
        window = GetCurrentWindow(); // call to set window->WriteAccessed = true;
17296
17297
0
    IM_ASSERT((flags & ImGuiDockNodeFlags_DockSpace) == 0);
17298
0
    IM_ASSERT(id != 0);
17299
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
17300
0
    if (!node)
17301
0
    {
17302
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X created\n", id);
17303
0
        node = DockContextAddNode(ctx, id);
17304
0
        node->SetLocalFlags(ImGuiDockNodeFlags_CentralNode);
17305
0
    }
17306
0
    if (window_class && window_class->ClassId != node->WindowClass.ClassId)
17307
0
        IMGUI_DEBUG_LOG_DOCKING("[docking] DockSpace: dockspace node 0x%08X: setup WindowClass 0x%08X -> 0x%08X\n", id, node->WindowClass.ClassId, window_class->ClassId);
17308
0
    node->SharedFlags = flags;
17309
0
    node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
17310
17311
    // When a DockSpace transitioned form implicit to explicit this may be called a second time
17312
    // It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
17313
0
    if (node->LastFrameActive == g.FrameCount && !(flags & ImGuiDockNodeFlags_KeepAliveOnly))
17314
0
    {
17315
0
        IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
17316
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17317
0
        return id;
17318
0
    }
17319
0
    node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_DockSpace);
17320
17321
    // Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
17322
0
    if (flags & ImGuiDockNodeFlags_KeepAliveOnly)
17323
0
    {
17324
0
        node->LastFrameAlive = g.FrameCount;
17325
0
        return id;
17326
0
    }
17327
17328
0
    const ImVec2 content_avail = GetContentRegionAvail();
17329
0
    ImVec2 size = ImFloor(size_arg);
17330
0
    if (size.x <= 0.0f)
17331
0
        size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
17332
0
    if (size.y <= 0.0f)
17333
0
        size.y = ImMax(content_avail.y + size.y, 4.0f);
17334
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17335
17336
0
    node->Pos = window->DC.CursorPos;
17337
0
    node->Size = node->SizeRef = size;
17338
0
    SetNextWindowPos(node->Pos);
17339
0
    SetNextWindowSize(node->Size);
17340
0
    g.NextWindowData.PosUndock = false;
17341
17342
    // FIXME-DOCK: Why do we need a child window to host a dockspace, could we host it in the existing window?
17343
    // FIXME-DOCK: What is the reason for not simply calling BeginChild()? (OK to have a reason but should be commented)
17344
0
    ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
17345
0
    window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
17346
0
    window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
17347
0
    window_flags |= ImGuiWindowFlags_NoBackground;
17348
17349
0
    char title[256];
17350
0
    ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
17351
17352
0
    PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
17353
0
    Begin(title, NULL, window_flags);
17354
0
    PopStyleVar();
17355
17356
0
    ImGuiWindow* host_window = g.CurrentWindow;
17357
0
    DockNodeSetupHostWindow(node, host_window);
17358
0
    host_window->ChildId = window->GetID(title);
17359
0
    node->OnlyNodeWithWindows = NULL;
17360
17361
0
    IM_ASSERT(node->IsRootNode());
17362
17363
    // We need to handle the rare case were a central node is missing.
17364
    // This can happen if the node was first created manually with DockBuilderAddNode() but _without_ the ImGuiDockNodeFlags_Dockspace.
17365
    // Doing it correctly would set the _CentralNode flags, which would then propagate according to subsequent split.
17366
    // It would also be ambiguous to attempt to assign a central node while there are split nodes, so we wait until there's a single node remaining.
17367
    // The specific sub-property of _CentralNode we are interested in recovering here is the "Don't delete when empty" property,
17368
    // as it doesn't make sense for an empty dockspace to not have this property.
17369
0
    if (node->IsLeafNode() && !node->IsCentralNode())
17370
0
        node->SetLocalFlags(node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17371
17372
    // Update the node
17373
0
    DockNodeUpdate(node);
17374
17375
0
    End();
17376
0
    ItemSize(size);
17377
0
    return id;
17378
0
}
17379
17380
// Tips: Use with ImGuiDockNodeFlags_PassthruCentralNode!
17381
// The limitation with this call is that your window won't have a menu bar.
17382
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
17383
// But you can also use BeginMainMenuBar(). If you really want a menu bar inside the same window as the one hosting the dockspace, you will need to copy this code somewhere and tweak it.
17384
ImGuiID ImGui::DockSpaceOverViewport(const ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
17385
0
{
17386
0
    if (viewport == NULL)
17387
0
        viewport = GetMainViewport();
17388
17389
0
    SetNextWindowPos(viewport->WorkPos);
17390
0
    SetNextWindowSize(viewport->WorkSize);
17391
0
    SetNextWindowViewport(viewport->ID);
17392
17393
0
    ImGuiWindowFlags host_window_flags = 0;
17394
0
    host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
17395
0
    host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
17396
0
    if (dockspace_flags & ImGuiDockNodeFlags_PassthruCentralNode)
17397
0
        host_window_flags |= ImGuiWindowFlags_NoBackground;
17398
17399
0
    char label[32];
17400
0
    ImFormatString(label, IM_ARRAYSIZE(label), "DockSpaceViewport_%08X", viewport->ID);
17401
17402
0
    PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
17403
0
    PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
17404
0
    PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
17405
0
    Begin(label, NULL, host_window_flags);
17406
0
    PopStyleVar(3);
17407
17408
0
    ImGuiID dockspace_id = GetID("DockSpace");
17409
0
    DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
17410
0
    End();
17411
17412
0
    return dockspace_id;
17413
0
}
17414
17415
//-----------------------------------------------------------------------------
17416
// Docking: Builder Functions
17417
//-----------------------------------------------------------------------------
17418
// Very early end-user API to manipulate dock nodes.
17419
// Only available in imgui_internal.h. Expect this API to change/break!
17420
// It is expected that those functions are all called _before_ the dockspace node submission.
17421
//-----------------------------------------------------------------------------
17422
// - DockBuilderDockWindow()
17423
// - DockBuilderGetNode()
17424
// - DockBuilderSetNodePos()
17425
// - DockBuilderSetNodeSize()
17426
// - DockBuilderAddNode()
17427
// - DockBuilderRemoveNode()
17428
// - DockBuilderRemoveNodeChildNodes()
17429
// - DockBuilderRemoveNodeDockedWindows()
17430
// - DockBuilderSplitNode()
17431
// - DockBuilderCopyNodeRec()
17432
// - DockBuilderCopyNode()
17433
// - DockBuilderCopyWindowSettings()
17434
// - DockBuilderCopyDockSpace()
17435
// - DockBuilderFinish()
17436
//-----------------------------------------------------------------------------
17437
17438
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
17439
0
{
17440
    // We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
17441
0
    ImGuiID window_id = ImHashStr(window_name);
17442
0
    if (ImGuiWindow* window = FindWindowByID(window_id))
17443
0
    {
17444
        // Apply to created window
17445
0
        SetWindowDock(window, node_id, ImGuiCond_Always);
17446
0
        window->DockOrder = -1;
17447
0
    }
17448
0
    else
17449
0
    {
17450
        // Apply to settings
17451
0
        ImGuiWindowSettings* settings = FindWindowSettingsByID(window_id);
17452
0
        if (settings == NULL)
17453
0
            settings = CreateNewWindowSettings(window_name);
17454
0
        settings->DockId = node_id;
17455
0
        settings->DockOrder = -1;
17456
0
    }
17457
0
}
17458
17459
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
17460
0
{
17461
0
    ImGuiContext* ctx = GImGui;
17462
0
    return DockContextFindNodeByID(ctx, node_id);
17463
0
}
17464
17465
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
17466
0
{
17467
0
    ImGuiContext* ctx = GImGui;
17468
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17469
0
    if (node == NULL)
17470
0
        return;
17471
0
    node->Pos = pos;
17472
0
    node->AuthorityForPos = ImGuiDataAuthority_DockNode;
17473
0
}
17474
17475
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
17476
0
{
17477
0
    ImGuiContext* ctx = GImGui;
17478
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17479
0
    if (node == NULL)
17480
0
        return;
17481
0
    IM_ASSERT(size.x > 0.0f && size.y > 0.0f);
17482
0
    node->Size = node->SizeRef = size;
17483
0
    node->AuthorityForSize = ImGuiDataAuthority_DockNode;
17484
0
}
17485
17486
// Make sure to use the ImGuiDockNodeFlags_DockSpace flag to create a dockspace node! Otherwise this will create a floating node!
17487
// - Floating node: you can then call DockBuilderSetNodePos()/DockBuilderSetNodeSize() to position and size the floating node.
17488
// - Dockspace node: calling DockBuilderSetNodePos() is unnecessary.
17489
// - If you intend to split a node immediately after creation using DockBuilderSplitNode(), make sure to call DockBuilderSetNodeSize() beforehand!
17490
//   For various reason, the splitting code currently needs a base size otherwise space may not be allocated as precisely as you would expect.
17491
// - Use (id == 0) to let the system allocate a node identifier.
17492
// - Existing node with a same id will be removed.
17493
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
17494
0
{
17495
0
    ImGuiContext* ctx = GImGui;
17496
17497
0
    if (id != 0)
17498
0
        DockBuilderRemoveNode(id);
17499
17500
0
    ImGuiDockNode* node = NULL;
17501
0
    if (flags & ImGuiDockNodeFlags_DockSpace)
17502
0
    {
17503
0
        DockSpace(id, ImVec2(0, 0), (flags & ~ImGuiDockNodeFlags_DockSpace) | ImGuiDockNodeFlags_KeepAliveOnly);
17504
0
        node = DockContextFindNodeByID(ctx, id);
17505
0
    }
17506
0
    else
17507
0
    {
17508
0
        node = DockContextAddNode(ctx, id);
17509
0
        node->SetLocalFlags(flags);
17510
0
    }
17511
0
    node->LastFrameAlive = ctx->FrameCount;   // Set this otherwise BeginDocked will undock during the same frame.
17512
0
    return node->ID;
17513
0
}
17514
17515
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
17516
0
{
17517
0
    ImGuiContext* ctx = GImGui;
17518
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
17519
0
    if (node == NULL)
17520
0
        return;
17521
0
    DockBuilderRemoveNodeDockedWindows(node_id, true);
17522
0
    DockBuilderRemoveNodeChildNodes(node_id);
17523
    // Node may have moved or deleted if e.g. any merge happened
17524
0
    node = DockContextFindNodeByID(ctx, node_id);
17525
0
    if (node == NULL)
17526
0
        return;
17527
0
    if (node->IsCentralNode() && node->ParentNode)
17528
0
        node->ParentNode->SetLocalFlags(node->ParentNode->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17529
0
    DockContextRemoveNode(ctx, node, true);
17530
0
}
17531
17532
// root_id = 0 to remove all, root_id != 0 to remove child of given node.
17533
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
17534
0
{
17535
0
    ImGuiContext* ctx = GImGui;
17536
0
    ImGuiDockContext* dc  = &ctx->DockContext;
17537
17538
0
    ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
17539
0
    if (root_id && root_node == NULL)
17540
0
        return;
17541
0
    bool has_central_node = false;
17542
17543
0
    ImGuiDataAuthority backup_root_node_authority_for_pos = root_node ? root_node->AuthorityForPos : ImGuiDataAuthority_Auto;
17544
0
    ImGuiDataAuthority backup_root_node_authority_for_size = root_node ? root_node->AuthorityForSize : ImGuiDataAuthority_Auto;
17545
17546
    // Process active windows
17547
0
    ImVector<ImGuiDockNode*> nodes_to_remove;
17548
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
17549
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
17550
0
        {
17551
0
            bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
17552
0
            if (want_removal)
17553
0
            {
17554
0
                if (node->IsCentralNode())
17555
0
                    has_central_node = true;
17556
0
                if (root_id != 0)
17557
0
                    DockContextQueueNotifyRemovedNode(ctx, node);
17558
0
                if (root_node)
17559
0
                {
17560
0
                    DockNodeMoveWindows(root_node, node);
17561
0
                    DockSettingsRenameNodeReferences(node->ID, root_node->ID);
17562
0
                }
17563
0
                nodes_to_remove.push_back(node);
17564
0
            }
17565
0
        }
17566
17567
    // DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
17568
    // Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
17569
0
    if (root_node)
17570
0
    {
17571
0
        root_node->AuthorityForPos = backup_root_node_authority_for_pos;
17572
0
        root_node->AuthorityForSize = backup_root_node_authority_for_size;
17573
0
    }
17574
17575
    // Apply to settings
17576
0
    for (ImGuiWindowSettings* settings = ctx->SettingsWindows.begin(); settings != NULL; settings = ctx->SettingsWindows.next_chunk(settings))
17577
0
        if (ImGuiID window_settings_dock_id = settings->DockId)
17578
0
            for (int n = 0; n < nodes_to_remove.Size; n++)
17579
0
                if (nodes_to_remove[n]->ID == window_settings_dock_id)
17580
0
                {
17581
0
                    settings->DockId = root_id;
17582
0
                    break;
17583
0
                }
17584
17585
    // Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
17586
0
    if (nodes_to_remove.Size > 1)
17587
0
        ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
17588
0
    for (int n = 0; n < nodes_to_remove.Size; n++)
17589
0
        DockContextRemoveNode(ctx, nodes_to_remove[n], false);
17590
17591
0
    if (root_id == 0)
17592
0
    {
17593
0
        dc->Nodes.Clear();
17594
0
        dc->Requests.clear();
17595
0
    }
17596
0
    else if (has_central_node)
17597
0
    {
17598
0
        root_node->CentralNode = root_node;
17599
0
        root_node->SetLocalFlags(root_node->LocalFlags | ImGuiDockNodeFlags_CentralNode);
17600
0
    }
17601
0
}
17602
17603
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_settings_refs)
17604
0
{
17605
    // Clear references in settings
17606
0
    ImGuiContext* ctx = GImGui;
17607
0
    ImGuiContext& g = *ctx;
17608
0
    if (clear_settings_refs)
17609
0
    {
17610
0
        for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
17611
0
        {
17612
0
            bool want_removal = (root_id == 0) || (settings->DockId == root_id);
17613
0
            if (!want_removal && settings->DockId != 0)
17614
0
                if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
17615
0
                    if (DockNodeGetRootNode(node)->ID == root_id)
17616
0
                        want_removal = true;
17617
0
            if (want_removal)
17618
0
                settings->DockId = 0;
17619
0
        }
17620
0
    }
17621
17622
    // Clear references in windows
17623
0
    for (int n = 0; n < g.Windows.Size; n++)
17624
0
    {
17625
0
        ImGuiWindow* window = g.Windows[n];
17626
0
        bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
17627
0
        if (want_removal)
17628
0
        {
17629
0
            const ImGuiID backup_dock_id = window->DockId;
17630
0
            IM_UNUSED(backup_dock_id);
17631
0
            DockContextProcessUndockWindow(ctx, window, clear_settings_refs);
17632
0
            if (!clear_settings_refs)
17633
0
                IM_ASSERT(window->DockId == backup_dock_id);
17634
0
        }
17635
0
    }
17636
0
}
17637
17638
// If 'out_id_at_dir' or 'out_id_at_opposite_dir' are non NULL, the function will write out the ID of the two new nodes created.
17639
// Return value is ID of the node at the specified direction, so same as (*out_id_at_dir) if that pointer is set.
17640
// FIXME-DOCK: We are not exposing nor using split_outer.
17641
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_at_opposite_dir)
17642
0
{
17643
0
    ImGuiContext& g = *GImGui;
17644
0
    IM_ASSERT(split_dir != ImGuiDir_None);
17645
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockBuilderSplitNode: node 0x%08X, split_dir %d\n", id, split_dir);
17646
17647
0
    ImGuiDockNode* node = DockContextFindNodeByID(&g, id);
17648
0
    if (node == NULL)
17649
0
    {
17650
0
        IM_ASSERT(node != NULL);
17651
0
        return 0;
17652
0
    }
17653
17654
0
    IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
17655
17656
0
    ImGuiDockRequest req;
17657
0
    req.Type = ImGuiDockRequestType_Split;
17658
0
    req.DockTargetWindow = NULL;
17659
0
    req.DockTargetNode = node;
17660
0
    req.DockPayload = NULL;
17661
0
    req.DockSplitDir = split_dir;
17662
0
    req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
17663
0
    req.DockSplitOuter = false;
17664
0
    DockContextProcessDock(&g, &req);
17665
17666
0
    ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
17667
0
    ImGuiID id_at_opposite_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
17668
0
    if (out_id_at_dir)
17669
0
        *out_id_at_dir = id_at_dir;
17670
0
    if (out_id_at_opposite_dir)
17671
0
        *out_id_at_opposite_dir = id_at_opposite_dir;
17672
0
    return id_at_dir;
17673
0
}
17674
17675
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
17676
0
{
17677
0
    ImGuiContext& g = *GImGui;
17678
0
    ImGuiDockNode* dst_node = ImGui::DockContextAddNode(&g, dst_node_id_if_known);
17679
0
    dst_node->SharedFlags = src_node->SharedFlags;
17680
0
    dst_node->LocalFlags = src_node->LocalFlags;
17681
0
    dst_node->LocalFlagsInWindows = ImGuiDockNodeFlags_None;
17682
0
    dst_node->Pos = src_node->Pos;
17683
0
    dst_node->Size = src_node->Size;
17684
0
    dst_node->SizeRef = src_node->SizeRef;
17685
0
    dst_node->SplitAxis = src_node->SplitAxis;
17686
0
    dst_node->UpdateMergedFlags();
17687
17688
0
    out_node_remap_pairs->push_back(src_node->ID);
17689
0
    out_node_remap_pairs->push_back(dst_node->ID);
17690
17691
0
    for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
17692
0
        if (src_node->ChildNodes[child_n])
17693
0
        {
17694
0
            dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
17695
0
            dst_node->ChildNodes[child_n]->ParentNode = dst_node;
17696
0
        }
17697
17698
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
17699
0
    return dst_node;
17700
0
}
17701
17702
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
17703
0
{
17704
0
    ImGuiContext* ctx = GImGui;
17705
0
    IM_ASSERT(src_node_id != 0);
17706
0
    IM_ASSERT(dst_node_id != 0);
17707
0
    IM_ASSERT(out_node_remap_pairs != NULL);
17708
17709
0
    DockBuilderRemoveNode(dst_node_id);
17710
17711
0
    ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
17712
0
    IM_ASSERT(src_node != NULL);
17713
17714
0
    out_node_remap_pairs->clear();
17715
0
    DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
17716
17717
0
    IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
17718
0
}
17719
17720
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
17721
0
{
17722
0
    ImGuiWindow* src_window = FindWindowByName(src_name);
17723
0
    if (src_window == NULL)
17724
0
        return;
17725
0
    if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
17726
0
    {
17727
0
        dst_window->Pos = src_window->Pos;
17728
0
        dst_window->Size = src_window->Size;
17729
0
        dst_window->SizeFull = src_window->SizeFull;
17730
0
        dst_window->Collapsed = src_window->Collapsed;
17731
0
    }
17732
0
    else
17733
0
    {
17734
0
        ImGuiWindowSettings* dst_settings = FindWindowSettingsByID(ImHashStr(dst_name));
17735
0
        if (!dst_settings)
17736
0
            dst_settings = CreateNewWindowSettings(dst_name);
17737
0
        ImVec2ih window_pos_2ih = ImVec2ih(src_window->Pos);
17738
0
        if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
17739
0
        {
17740
0
            dst_settings->ViewportPos = window_pos_2ih;
17741
0
            dst_settings->ViewportId = src_window->ViewportId;
17742
0
            dst_settings->Pos = ImVec2ih(0, 0);
17743
0
        }
17744
0
        else
17745
0
        {
17746
0
            dst_settings->Pos = window_pos_2ih;
17747
0
        }
17748
0
        dst_settings->Size = ImVec2ih(src_window->SizeFull);
17749
0
        dst_settings->Collapsed = src_window->Collapsed;
17750
0
    }
17751
0
}
17752
17753
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
17754
void ImGui::DockBuilderCopyDockSpace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
17755
0
{
17756
0
    ImGuiContext& g = *GImGui;
17757
0
    IM_ASSERT(src_dockspace_id != 0);
17758
0
    IM_ASSERT(dst_dockspace_id != 0);
17759
0
    IM_ASSERT(in_window_remap_pairs != NULL);
17760
0
    IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
17761
17762
    // Duplicate entire dock
17763
    // FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
17764
    // whereas we could attempt to at least keep them together in a new, same floating node.
17765
0
    ImVector<ImGuiID> node_remap_pairs;
17766
0
    DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
17767
17768
    // Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
17769
    // (The windows associated to src_dockspace_id are staying in place)
17770
0
    ImVector<ImGuiID> src_windows;
17771
0
    for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
17772
0
    {
17773
0
        const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
17774
0
        const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
17775
0
        ImGuiID src_window_id = ImHashStr(src_window_name);
17776
0
        src_windows.push_back(src_window_id);
17777
17778
        // Search in the remapping tables
17779
0
        ImGuiID src_dock_id = 0;
17780
0
        if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
17781
0
            src_dock_id = src_window->DockId;
17782
0
        else if (ImGuiWindowSettings* src_window_settings = FindWindowSettingsByID(src_window_id))
17783
0
            src_dock_id = src_window_settings->DockId;
17784
0
        ImGuiID dst_dock_id = 0;
17785
0
        for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17786
0
            if (node_remap_pairs[dock_remap_n] == src_dock_id)
17787
0
            {
17788
0
                dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17789
                //node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
17790
0
                break;
17791
0
            }
17792
17793
0
        if (dst_dock_id != 0)
17794
0
        {
17795
            // Docked windows gets redocked into the new node hierarchy.
17796
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap live window '%s' 0x%08X -> '%s' 0x%08X\n", src_window_name, src_dock_id, dst_window_name, dst_dock_id);
17797
0
            DockBuilderDockWindow(dst_window_name, dst_dock_id);
17798
0
        }
17799
0
        else
17800
0
        {
17801
            // Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
17802
            // When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
17803
0
            IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window settings '%s' -> '%s'\n", src_window_name, dst_window_name);
17804
0
            DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
17805
0
        }
17806
0
    }
17807
17808
    // Anything else in the source nodes of 'node_remap_pairs' are windows that are not included in the remapping list.
17809
    // Find those windows and move to them to the cloned dock node. This may be optional?
17810
    // Dock those are a second step as undocking would invalidate source dock nodes.
17811
0
    struct DockRemainingWindowTask { ImGuiWindow* Window; ImGuiID DockId; DockRemainingWindowTask(ImGuiWindow* window, ImGuiID dock_id) { Window = window; DockId = dock_id; } };
17812
0
    ImVector<DockRemainingWindowTask> dock_remaining_windows;
17813
0
    for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
17814
0
        if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
17815
0
        {
17816
0
            ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
17817
0
            ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
17818
0
            for (int window_n = 0; window_n < node->Windows.Size; window_n++)
17819
0
            {
17820
0
                ImGuiWindow* window = node->Windows[window_n];
17821
0
                if (src_windows.contains(window->ID))
17822
0
                    continue;
17823
17824
                // Docked windows gets redocked into the new node hierarchy.
17825
0
                IMGUI_DEBUG_LOG_DOCKING("[docking] Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
17826
0
                dock_remaining_windows.push_back(DockRemainingWindowTask(window, dst_dock_id));
17827
0
            }
17828
0
        }
17829
0
    for (const DockRemainingWindowTask& task : dock_remaining_windows)
17830
0
        DockBuilderDockWindow(task.Window->Name, task.DockId);
17831
0
}
17832
17833
// FIXME-DOCK: This is awkward because in series of split user is likely to loose access to its root node.
17834
void ImGui::DockBuilderFinish(ImGuiID root_id)
17835
0
{
17836
0
    ImGuiContext* ctx = GImGui;
17837
    //DockContextRebuild(ctx);
17838
0
    DockContextBuildAddWindowsToNodes(ctx, root_id);
17839
0
}
17840
17841
//-----------------------------------------------------------------------------
17842
// Docking: Begin/End Support Functions (called from Begin/End)
17843
//-----------------------------------------------------------------------------
17844
// - GetWindowAlwaysWantOwnTabBar()
17845
// - DockContextBindNodeToWindow()
17846
// - BeginDocked()
17847
// - BeginDockableDragDropSource()
17848
// - BeginDockableDragDropTarget()
17849
//-----------------------------------------------------------------------------
17850
17851
bool ImGui::GetWindowAlwaysWantOwnTabBar(ImGuiWindow* window)
17852
71.9k
{
17853
71.9k
    ImGuiContext& g = *GImGui;
17854
71.9k
    if (g.IO.ConfigDockingAlwaysTabBar || window->WindowClass.DockingAlwaysTabBar)
17855
0
        if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) == 0)
17856
0
            if (!window->IsFallbackWindow)    // We don't support AlwaysTabBar on the fallback/implicit window to avoid unused dock-node overhead/noise
17857
0
                return true;
17858
71.9k
    return false;
17859
71.9k
}
17860
17861
static ImGuiDockNode* ImGui::DockContextBindNodeToWindow(ImGuiContext* ctx, ImGuiWindow* window)
17862
0
{
17863
0
    ImGuiContext& g = *ctx;
17864
0
    ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
17865
0
    IM_ASSERT(window->DockNode == NULL);
17866
17867
    // We should not be docking into a split node (SetWindowDock should avoid this)
17868
0
    if (node && node->IsSplitNode())
17869
0
    {
17870
0
        DockContextProcessUndockWindow(ctx, window);
17871
0
        return NULL;
17872
0
    }
17873
17874
    // Create node
17875
0
    if (node == NULL)
17876
0
    {
17877
0
        node = DockContextAddNode(ctx, window->DockId);
17878
0
        node->AuthorityForPos = node->AuthorityForSize = node->AuthorityForViewport = ImGuiDataAuthority_Window;
17879
0
        node->LastFrameAlive = g.FrameCount;
17880
0
    }
17881
17882
    // If the node just turned visible and is part of a hierarchy, it doesn't have a Size assigned by DockNodeTreeUpdatePosSize() yet,
17883
    // so we're forcing a Pos/Size update from the first ancestor that is already visible (often it will be the root node).
17884
    // If we don't do this, the window will be assigned a zero-size on its first frame, which won't ideally warm up the layout.
17885
    // This is a little wonky because we don't normally update the Pos/Size of visible node mid-frame.
17886
0
    if (!node->IsVisible)
17887
0
    {
17888
0
        ImGuiDockNode* ancestor_node = node;
17889
0
        while (!ancestor_node->IsVisible && ancestor_node->ParentNode)
17890
0
            ancestor_node = ancestor_node->ParentNode;
17891
0
        IM_ASSERT(ancestor_node->Size.x > 0.0f && ancestor_node->Size.y > 0.0f);
17892
0
        DockNodeUpdateHasCentralNodeChild(DockNodeGetRootNode(ancestor_node));
17893
0
        DockNodeTreeUpdatePosSize(ancestor_node, ancestor_node->Pos, ancestor_node->Size, node);
17894
0
    }
17895
17896
    // Add window to node
17897
0
    bool node_was_visible = node->IsVisible;
17898
0
    DockNodeAddWindow(node, window, true);
17899
0
    node->IsVisible = node_was_visible; // Don't mark visible right away (so DockContextEndFrame() doesn't render it, maybe other side effects? will see)
17900
0
    IM_ASSERT(node == window->DockNode);
17901
0
    return node;
17902
0
}
17903
17904
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
17905
0
{
17906
0
    ImGuiContext* ctx = GImGui;
17907
0
    ImGuiContext& g = *ctx;
17908
17909
    // Clear fields ahead so most early-out paths don't have to do it
17910
0
    window->DockIsActive = window->DockNodeIsVisible = window->DockTabIsVisible = false;
17911
17912
0
    const bool auto_dock_node = GetWindowAlwaysWantOwnTabBar(window);
17913
0
    if (auto_dock_node)
17914
0
    {
17915
0
        if (window->DockId == 0)
17916
0
        {
17917
0
            IM_ASSERT(window->DockNode == NULL);
17918
0
            window->DockId = DockContextGenNodeID(ctx);
17919
0
        }
17920
0
    }
17921
0
    else
17922
0
    {
17923
        // Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
17924
0
        bool want_undock = false;
17925
0
        want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
17926
0
        want_undock |= (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock;
17927
0
        if (want_undock)
17928
0
        {
17929
0
            DockContextProcessUndockWindow(ctx, window);
17930
0
            return;
17931
0
        }
17932
0
    }
17933
17934
    // Bind to our dock node
17935
0
    ImGuiDockNode* node = window->DockNode;
17936
0
    if (node != NULL)
17937
0
        IM_ASSERT(window->DockId == node->ID);
17938
0
    if (window->DockId != 0 && node == NULL)
17939
0
    {
17940
0
        node = DockContextBindNodeToWindow(ctx, window);
17941
0
        if (node == NULL)
17942
0
            return;
17943
0
    }
17944
17945
#if 0
17946
    // Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
17947
    if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
17948
    {
17949
        DockContextProcessUndockWindow(ctx, window);
17950
        return;
17951
    }
17952
#endif
17953
17954
    // Undock if our dockspace node disappeared
17955
    // Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
17956
0
    if (node->LastFrameAlive < g.FrameCount)
17957
0
    {
17958
        // If the window has been orphaned, transition the docknode to an implicit node processed in DockContextNewFrameUpdateDocking()
17959
0
        ImGuiDockNode* root_node = DockNodeGetRootNode(node);
17960
0
        if (root_node->LastFrameAlive < g.FrameCount)
17961
0
            DockContextProcessUndockWindow(ctx, window);
17962
0
        else
17963
0
            window->DockIsActive = true;
17964
0
        return;
17965
0
    }
17966
17967
    // Store style overrides
17968
0
    for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
17969
0
        window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
17970
17971
    // Fast path return. It is common for windows to hold on a persistent DockId but be the only visible window,
17972
    // and never create neither a host window neither a tab bar.
17973
    // FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
17974
0
    if (node->HostWindow == NULL)
17975
0
    {
17976
0
        if (node->State == ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing)
17977
0
            window->DockIsActive = true;
17978
0
        if (node->Windows.Size > 1)
17979
0
            DockNodeHideWindowDuringHostWindowCreation(window);
17980
0
        return;
17981
0
    }
17982
17983
    // We can have zero-sized nodes (e.g. children of a small-size dockspace)
17984
0
    IM_ASSERT(node->HostWindow);
17985
0
    IM_ASSERT(node->IsLeafNode());
17986
0
    IM_ASSERT(node->Size.x >= 0.0f && node->Size.y >= 0.0f);
17987
0
    node->State = ImGuiDockNodeState_HostWindowVisible;
17988
17989
    // Undock if we are submitted earlier than the host window
17990
0
    if (!(node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly) && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
17991
0
    {
17992
0
        DockContextProcessUndockWindow(ctx, window);
17993
0
        return;
17994
0
    }
17995
17996
    // Position/Size window
17997
0
    SetNextWindowPos(node->Pos);
17998
0
    SetNextWindowSize(node->Size);
17999
0
    g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
18000
0
    window->DockIsActive = true;
18001
0
    window->DockNodeIsVisible = true;
18002
0
    window->DockTabIsVisible = false;
18003
0
    if (node->MergedFlags & ImGuiDockNodeFlags_KeepAliveOnly)
18004
0
        return;
18005
18006
    // When the window is selected we mark it as visible.
18007
0
    if (node->VisibleWindow == window)
18008
0
        window->DockTabIsVisible = true;
18009
18010
    // Update window flag
18011
0
    IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
18012
0
    window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
18013
0
    if (node->IsHiddenTabBar() || node->IsNoTabBar())
18014
0
        window->Flags |= ImGuiWindowFlags_NoTitleBar;
18015
0
    else
18016
0
        window->Flags &= ~ImGuiWindowFlags_NoTitleBar;      // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
18017
18018
    // Save new dock order only if the window has been visible once already
18019
    // This allows multiple windows to be created in the same frame and have their respective dock orders preserved.
18020
0
    if (node->TabBar && window->WasActive)
18021
0
        window->DockOrder = (short)DockNodeGetTabOrder(window);
18022
18023
0
    if ((node->WantCloseAll || node->WantCloseTabId == window->TabId) && p_open != NULL)
18024
0
        *p_open = false;
18025
18026
    // Update ChildId to allow returning from Child to Parent with Escape
18027
0
    ImGuiWindow* parent_window = window->DockNode->HostWindow;
18028
0
    window->ChildId = parent_window->GetID(window->Name);
18029
0
}
18030
18031
void ImGui::BeginDockableDragDropSource(ImGuiWindow* window)
18032
120
{
18033
120
    ImGuiContext& g = *GImGui;
18034
120
    IM_ASSERT(g.ActiveId == window->MoveId);
18035
120
    IM_ASSERT(g.MovingWindow == window);
18036
120
    IM_ASSERT(g.CurrentWindow == window);
18037
18038
120
    g.LastItemData.ID = window->MoveId;
18039
120
    window = window->RootWindowDockTree;
18040
120
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18041
120
    bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset); // FIXME-DOCKING: Need to make this stateful and explicit
18042
120
    if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
18043
75
    {
18044
75
        SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
18045
75
        EndDragDropSource();
18046
18047
        // Store style overrides
18048
525
        for (int color_n = 0; color_n < ImGuiWindowDockStyleCol_COUNT; color_n++)
18049
450
            window->DockStyle.Colors[color_n] = ColorConvertFloat4ToU32(g.Style.Colors[GWindowDockStyleColors[color_n]]);
18050
75
    }
18051
120
}
18052
18053
void ImGui::BeginDockableDragDropTarget(ImGuiWindow* window)
18054
140
{
18055
140
    ImGuiContext* ctx = GImGui;
18056
140
    ImGuiContext& g = *ctx;
18057
18058
    //IM_ASSERT(window->RootWindowDockTree == window); // May also be a DockSpace
18059
140
    IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
18060
140
    if (!g.DragDropActive)
18061
0
        return;
18062
    //GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
18063
140
    if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
18064
136
        return;
18065
18066
    // Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
18067
    // (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
18068
4
    const ImGuiPayload* payload = &g.DragDropPayload;
18069
4
    if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
18070
0
    {
18071
0
        EndDragDropTarget();
18072
0
        return;
18073
0
    }
18074
18075
4
    ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
18076
4
    if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
18077
4
    {
18078
        // Select target node
18079
        // (Important: we cannot use g.HoveredDockNode here! Because each of our target node have filters based on payload, each candidate drop target will do its own evaluation)
18080
4
        bool dock_into_floating_window = false;
18081
4
        ImGuiDockNode* node = NULL;
18082
4
        if (window->DockNodeAsHost)
18083
0
        {
18084
            // Cannot assume that node will != NULL even though we passed the rectangle test: it depends on padding/spacing handled by DockNodeTreeFindVisibleNodeByPos().
18085
0
            node = DockNodeTreeFindVisibleNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
18086
18087
            // There is an edge case when docking into a dockspace which only has _inactive_ nodes (because none of the windows are active)
18088
            // In this case we need to fallback into any leaf mode, possibly the central node.
18089
            // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
18090
0
            if (node && node->IsDockSpace() && node->IsRootNode())
18091
0
                node = (node->CentralNode && node->IsLeafNode()) ? node->CentralNode : DockNodeTreeFindFallbackLeafNode(node);
18092
0
        }
18093
4
        else
18094
4
        {
18095
4
            if (window->DockNode)
18096
0
                node = window->DockNode;
18097
4
            else
18098
4
                dock_into_floating_window = true; // Dock into a regular window
18099
4
        }
18100
18101
4
        const ImRect explicit_target_rect = (node && node->TabBar && !node->IsHiddenTabBar() && !node->IsNoTabBar()) ? node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
18102
4
        const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
18103
18104
        // Preview docking request and find out split direction/ratio
18105
        //const bool do_preview = true;     // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
18106
4
        const bool do_preview = payload->IsPreview() || payload->IsDelivery();
18107
4
        if (do_preview && (node != NULL || dock_into_floating_window))
18108
0
        {
18109
            // If we have a non-leaf node it means we are hovering the border of a parent node, in which case only outer markers will appear.
18110
0
            ImGuiDockPreviewData split_inner;
18111
0
            ImGuiDockPreviewData split_outer;
18112
0
            ImGuiDockPreviewData* split_data = &split_inner;
18113
0
            if (node && (node->ParentNode || node->IsCentralNode() || !node->IsLeafNode()))
18114
0
                if (ImGuiDockNode* root_node = DockNodeGetRootNode(node))
18115
0
                {
18116
0
                    DockNodePreviewDockSetup(window, root_node, payload_window, NULL, &split_outer, is_explicit_target, true);
18117
0
                    if (split_outer.IsSplitDirExplicit)
18118
0
                        split_data = &split_outer;
18119
0
                }
18120
0
            if (!node || node->IsLeafNode())
18121
0
                DockNodePreviewDockSetup(window, node, payload_window, NULL, &split_inner, is_explicit_target, false);
18122
0
            if (split_data == &split_outer)
18123
0
                split_inner.IsDropAllowed = false;
18124
18125
            // Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
18126
0
            DockNodePreviewDockRender(window, node, payload_window, &split_inner);
18127
0
            DockNodePreviewDockRender(window, node, payload_window, &split_outer);
18128
18129
            // Queue docking request
18130
0
            if (split_data->IsDropAllowed && payload->IsDelivery())
18131
0
                DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
18132
0
        }
18133
4
    }
18134
4
    EndDragDropTarget();
18135
4
}
18136
18137
//-----------------------------------------------------------------------------
18138
// Docking: Settings
18139
//-----------------------------------------------------------------------------
18140
// - DockSettingsRenameNodeReferences()
18141
// - DockSettingsRemoveNodeReferences()
18142
// - DockSettingsFindNodeSettings()
18143
// - DockSettingsHandler_ApplyAll()
18144
// - DockSettingsHandler_ReadOpen()
18145
// - DockSettingsHandler_ReadLine()
18146
// - DockSettingsHandler_DockNodeToSettings()
18147
// - DockSettingsHandler_WriteAll()
18148
//-----------------------------------------------------------------------------
18149
18150
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
18151
0
{
18152
0
    ImGuiContext& g = *GImGui;
18153
0
    IMGUI_DEBUG_LOG_DOCKING("[docking] DockSettingsRenameNodeReferences: from 0x%08X -> to 0x%08X\n", old_node_id, new_node_id);
18154
0
    for (int window_n = 0; window_n < g.Windows.Size; window_n++)
18155
0
    {
18156
0
        ImGuiWindow* window = g.Windows[window_n];
18157
0
        if (window->DockId == old_node_id && window->DockNode == NULL)
18158
0
            window->DockId = new_node_id;
18159
0
    }
18160
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18161
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18162
0
        if (settings->DockId == old_node_id)
18163
0
            settings->DockId = new_node_id;
18164
0
}
18165
18166
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
18167
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
18168
0
{
18169
0
    ImGuiContext& g = *GImGui;
18170
0
    int found = 0;
18171
    //// FIXME-OPT: We could remove this loop by storing the index in the map
18172
0
    for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18173
0
        for (int node_n = 0; node_n < node_ids_count; node_n++)
18174
0
            if (settings->DockId == node_ids[node_n])
18175
0
            {
18176
0
                settings->DockId = 0;
18177
0
                settings->DockOrder = -1;
18178
0
                if (++found < node_ids_count)
18179
0
                    break;
18180
0
                return;
18181
0
            }
18182
0
}
18183
18184
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
18185
0
{
18186
    // FIXME-OPT
18187
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18188
0
    for (int n = 0; n < dc->NodesSettings.Size; n++)
18189
0
        if (dc->NodesSettings[n].ID == id)
18190
0
            return &dc->NodesSettings[n];
18191
0
    return NULL;
18192
0
}
18193
18194
// Clear settings data
18195
static void ImGui::DockSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18196
0
{
18197
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18198
0
    dc->NodesSettings.clear();
18199
0
    DockContextClearNodes(ctx, 0, true);
18200
0
}
18201
18202
// Recreate nodes based on settings data
18203
static void ImGui::DockSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
18204
0
{
18205
    // Prune settings at boot time only
18206
0
    ImGuiDockContext* dc  = &ctx->DockContext;
18207
0
    if (ctx->Windows.Size == 0)
18208
0
        DockContextPruneUnusedSettingsNodes(ctx);
18209
0
    DockContextBuildNodesFromSettings(ctx, dc->NodesSettings.Data, dc->NodesSettings.Size);
18210
0
    DockContextBuildAddWindowsToNodes(ctx, 0);
18211
0
}
18212
18213
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
18214
0
{
18215
0
    if (strcmp(name, "Data") != 0)
18216
0
        return NULL;
18217
0
    return (void*)1;
18218
0
}
18219
18220
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
18221
0
{
18222
0
    char c = 0;
18223
0
    int x = 0, y = 0;
18224
0
    int r = 0;
18225
18226
    // Parsing, e.g.
18227
    // " DockNode   ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
18228
    // "   DockNode ID=0x00000002 Parent=0x00000001 "
18229
    // Important: this code expect currently fields in a fixed order.
18230
0
    ImGuiDockNodeSettings node;
18231
0
    line = ImStrSkipBlank(line);
18232
0
    if      (strncmp(line, "DockNode", 8) == 0)  { line = ImStrSkipBlank(line + strlen("DockNode")); }
18233
0
    else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.Flags |= ImGuiDockNodeFlags_DockSpace; }
18234
0
    else return;
18235
0
    if (sscanf(line, "ID=0x%08X%n",      &node.ID, &r) == 1)            { line += r; } else return;
18236
0
    if (sscanf(line, " Parent=0x%08X%n", &node.ParentNodeId, &r) == 1)  { line += r; if (node.ParentNodeId == 0) return; }
18237
0
    if (sscanf(line, " Window=0x%08X%n", &node.ParentWindowId, &r) ==1) { line += r; if (node.ParentWindowId == 0) return; }
18238
0
    if (node.ParentNodeId == 0)
18239
0
    {
18240
0
        if (sscanf(line, " Pos=%i,%i%n",  &x, &y, &r) == 2)         { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
18241
0
        if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2)         { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
18242
0
    }
18243
0
    else
18244
0
    {
18245
0
        if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2)      { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
18246
0
    }
18247
0
    if (sscanf(line, " Split=%c%n", &c, &r) == 1)                   { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
18248
0
    if (sscanf(line, " NoResize=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoResize; }
18249
0
    if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1)             { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_CentralNode; }
18250
0
    if (sscanf(line, " NoTabBar=%d%n", &x, &r) == 1)                { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoTabBar; }
18251
0
    if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1)            { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_HiddenTabBar; }
18252
0
    if (sscanf(line, " NoWindowMenuButton=%d%n", &x, &r) == 1)      { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoWindowMenuButton; }
18253
0
    if (sscanf(line, " NoCloseButton=%d%n", &x, &r) == 1)           { line += r; if (x != 0) node.Flags |= ImGuiDockNodeFlags_NoCloseButton; }
18254
0
    if (sscanf(line, " Selected=0x%08X%n", &node.SelectedTabId,&r) == 1) { line += r; }
18255
0
    if (node.ParentNodeId != 0)
18256
0
        if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentNodeId))
18257
0
            node.Depth = parent_settings->Depth + 1;
18258
0
    ctx->DockContext.NodesSettings.push_back(node);
18259
0
}
18260
18261
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
18262
0
{
18263
0
    ImGuiDockNodeSettings node_settings;
18264
0
    IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
18265
0
    node_settings.ID = node->ID;
18266
0
    node_settings.ParentNodeId = node->ParentNode ? node->ParentNode->ID : 0;
18267
0
    node_settings.ParentWindowId = (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow) ? node->HostWindow->ParentWindow->ID : 0;
18268
0
    node_settings.SelectedTabId = node->SelectedTabId;
18269
0
    node_settings.SplitAxis = (signed char)(node->IsSplitNode() ? node->SplitAxis : ImGuiAxis_None);
18270
0
    node_settings.Depth = (char)depth;
18271
0
    node_settings.Flags = (node->LocalFlags & ImGuiDockNodeFlags_SavedFlagsMask_);
18272
0
    node_settings.Pos = ImVec2ih(node->Pos);
18273
0
    node_settings.Size = ImVec2ih(node->Size);
18274
0
    node_settings.SizeRef = ImVec2ih(node->SizeRef);
18275
0
    dc->NodesSettings.push_back(node_settings);
18276
0
    if (node->ChildNodes[0])
18277
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
18278
0
    if (node->ChildNodes[1])
18279
0
        DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
18280
0
}
18281
18282
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
18283
0
{
18284
0
    ImGuiContext& g = *ctx;
18285
0
    ImGuiDockContext* dc = &ctx->DockContext;
18286
0
    if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
18287
0
        return;
18288
18289
    // Gather settings data
18290
    // (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
18291
0
    dc->NodesSettings.resize(0);
18292
0
    dc->NodesSettings.reserve(dc->Nodes.Data.Size);
18293
0
    for (int n = 0; n < dc->Nodes.Data.Size; n++)
18294
0
        if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
18295
0
            if (node->IsRootNode())
18296
0
                DockSettingsHandler_DockNodeToSettings(dc, node, 0);
18297
18298
0
    int max_depth = 0;
18299
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18300
0
        max_depth = ImMax((int)dc->NodesSettings[node_n].Depth, max_depth);
18301
18302
    // Write to text buffer
18303
0
    buf->appendf("[%s][Data]\n", handler->TypeName);
18304
0
    for (int node_n = 0; node_n < dc->NodesSettings.Size; node_n++)
18305
0
    {
18306
0
        const int line_start_pos = buf->size(); (void)line_start_pos;
18307
0
        const ImGuiDockNodeSettings* node_settings = &dc->NodesSettings[node_n];
18308
0
        buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", (node_settings->Flags & ImGuiDockNodeFlags_DockSpace) ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, "");  // Text align nodes to facilitate looking at .ini file
18309
0
        buf->appendf(" ID=0x%08X", node_settings->ID);
18310
0
        if (node_settings->ParentNodeId)
18311
0
        {
18312
0
            buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentNodeId, node_settings->SizeRef.x, node_settings->SizeRef.y);
18313
0
        }
18314
0
        else
18315
0
        {
18316
0
            if (node_settings->ParentWindowId)
18317
0
                buf->appendf(" Window=0x%08X", node_settings->ParentWindowId);
18318
0
            buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
18319
0
        }
18320
0
        if (node_settings->SplitAxis != ImGuiAxis_None)
18321
0
            buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
18322
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoResize)
18323
0
            buf->appendf(" NoResize=1");
18324
0
        if (node_settings->Flags & ImGuiDockNodeFlags_CentralNode)
18325
0
            buf->appendf(" CentralNode=1");
18326
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoTabBar)
18327
0
            buf->appendf(" NoTabBar=1");
18328
0
        if (node_settings->Flags & ImGuiDockNodeFlags_HiddenTabBar)
18329
0
            buf->appendf(" HiddenTabBar=1");
18330
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoWindowMenuButton)
18331
0
            buf->appendf(" NoWindowMenuButton=1");
18332
0
        if (node_settings->Flags & ImGuiDockNodeFlags_NoCloseButton)
18333
0
            buf->appendf(" NoCloseButton=1");
18334
0
        if (node_settings->SelectedTabId)
18335
0
            buf->appendf(" Selected=0x%08X", node_settings->SelectedTabId);
18336
18337
#if IMGUI_DEBUG_INI_SETTINGS
18338
        // [DEBUG] Include comments in the .ini file to ease debugging
18339
        if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
18340
        {
18341
            buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), "");     // Align everything
18342
            if (node->IsDockSpace() && node->HostWindow && node->HostWindow->ParentWindow)
18343
                buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
18344
            // Iterate settings so we can give info about windows that didn't exist during the session.
18345
            int contains_window = 0;
18346
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
18347
                if (settings->DockId == node_settings->ID)
18348
                {
18349
                    if (contains_window++ == 0)
18350
                        buf->appendf(" ; contains ");
18351
                    buf->appendf("'%s' ", settings->GetName());
18352
                }
18353
        }
18354
#endif
18355
0
        buf->appendf("\n");
18356
0
    }
18357
0
    buf->appendf("\n");
18358
0
}
18359
18360
18361
//-----------------------------------------------------------------------------
18362
// [SECTION] PLATFORM DEPENDENT HELPERS
18363
//-----------------------------------------------------------------------------
18364
18365
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
18366
18367
#ifdef _MSC_VER
18368
#pragma comment(lib, "user32")
18369
#pragma comment(lib, "kernel32")
18370
#endif
18371
18372
// Win32 clipboard implementation
18373
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
18374
static const char* GetClipboardTextFn_DefaultImpl(void*)
18375
{
18376
    ImGuiContext& g = *GImGui;
18377
    g.ClipboardHandlerData.clear();
18378
    if (!::OpenClipboard(NULL))
18379
        return NULL;
18380
    HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
18381
    if (wbuf_handle == NULL)
18382
    {
18383
        ::CloseClipboard();
18384
        return NULL;
18385
    }
18386
    if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
18387
    {
18388
        int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
18389
        g.ClipboardHandlerData.resize(buf_len);
18390
        ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
18391
    }
18392
    ::GlobalUnlock(wbuf_handle);
18393
    ::CloseClipboard();
18394
    return g.ClipboardHandlerData.Data;
18395
}
18396
18397
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18398
{
18399
    if (!::OpenClipboard(NULL))
18400
        return;
18401
    const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
18402
    HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
18403
    if (wbuf_handle == NULL)
18404
    {
18405
        ::CloseClipboard();
18406
        return;
18407
    }
18408
    WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
18409
    ::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
18410
    ::GlobalUnlock(wbuf_handle);
18411
    ::EmptyClipboard();
18412
    if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
18413
        ::GlobalFree(wbuf_handle);
18414
    ::CloseClipboard();
18415
}
18416
18417
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
18418
18419
#include <Carbon/Carbon.h>  // Use old API to avoid need for separate .mm file
18420
static PasteboardRef main_clipboard = 0;
18421
18422
// OSX clipboard implementation
18423
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
18424
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18425
{
18426
    if (!main_clipboard)
18427
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18428
    PasteboardClear(main_clipboard);
18429
    CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
18430
    if (cf_data)
18431
    {
18432
        PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
18433
        CFRelease(cf_data);
18434
    }
18435
}
18436
18437
static const char* GetClipboardTextFn_DefaultImpl(void*)
18438
{
18439
    if (!main_clipboard)
18440
        PasteboardCreate(kPasteboardClipboard, &main_clipboard);
18441
    PasteboardSynchronize(main_clipboard);
18442
18443
    ItemCount item_count = 0;
18444
    PasteboardGetItemCount(main_clipboard, &item_count);
18445
    for (ItemCount i = 0; i < item_count; i++)
18446
    {
18447
        PasteboardItemID item_id = 0;
18448
        PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
18449
        CFArrayRef flavor_type_array = 0;
18450
        PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
18451
        for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
18452
        {
18453
            CFDataRef cf_data;
18454
            if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
18455
            {
18456
                ImGuiContext& g = *GImGui;
18457
                g.ClipboardHandlerData.clear();
18458
                int length = (int)CFDataGetLength(cf_data);
18459
                g.ClipboardHandlerData.resize(length + 1);
18460
                CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
18461
                g.ClipboardHandlerData[length] = 0;
18462
                CFRelease(cf_data);
18463
                return g.ClipboardHandlerData.Data;
18464
            }
18465
        }
18466
    }
18467
    return NULL;
18468
}
18469
18470
#else
18471
18472
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
18473
static const char* GetClipboardTextFn_DefaultImpl(void*)
18474
0
{
18475
0
    ImGuiContext& g = *GImGui;
18476
0
    return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
18477
0
}
18478
18479
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
18480
0
{
18481
0
    ImGuiContext& g = *GImGui;
18482
0
    g.ClipboardHandlerData.clear();
18483
0
    const char* text_end = text + strlen(text);
18484
0
    g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
18485
0
    memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
18486
0
    g.ClipboardHandlerData[(int)(text_end - text)] = 0;
18487
0
}
18488
18489
#endif
18490
18491
// Win32 API IME support (for Asian languages, etc.)
18492
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
18493
18494
#include <imm.h>
18495
#ifdef _MSC_VER
18496
#pragma comment(lib, "imm32")
18497
#endif
18498
18499
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport* viewport, ImGuiPlatformImeData* data)
18500
{
18501
    // Notify OS Input Method Editor of text input position
18502
    HWND hwnd = (HWND)viewport->PlatformHandleRaw;
18503
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
18504
    if (hwnd == 0)
18505
        hwnd = (HWND)ImGui::GetIO().ImeWindowHandle;
18506
#endif
18507
    if (hwnd == 0)
18508
        return;
18509
18510
    //::ImmAssociateContextEx(hwnd, NULL, data->WantVisible ? IACE_DEFAULT : 0);
18511
    if (HIMC himc = ::ImmGetContext(hwnd))
18512
    {
18513
        COMPOSITIONFORM composition_form = {};
18514
        composition_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18515
        composition_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18516
        composition_form.dwStyle = CFS_FORCE_POSITION;
18517
        ::ImmSetCompositionWindow(himc, &composition_form);
18518
        CANDIDATEFORM candidate_form = {};
18519
        candidate_form.dwStyle = CFS_CANDIDATEPOS;
18520
        candidate_form.ptCurrentPos.x = (LONG)(data->InputPos.x - viewport->Pos.x);
18521
        candidate_form.ptCurrentPos.y = (LONG)(data->InputPos.y - viewport->Pos.y);
18522
        ::ImmSetCandidateWindow(himc, &candidate_form);
18523
        ::ImmReleaseContext(hwnd, himc);
18524
    }
18525
}
18526
18527
#else
18528
18529
0
static void SetPlatformImeDataFn_DefaultImpl(ImGuiViewport*, ImGuiPlatformImeData*) {}
18530
18531
#endif
18532
18533
//-----------------------------------------------------------------------------
18534
// [SECTION] METRICS/DEBUGGER WINDOW
18535
//-----------------------------------------------------------------------------
18536
// - RenderViewportThumbnail() [Internal]
18537
// - RenderViewportsThumbnails() [Internal]
18538
// - DebugTextEncoding()
18539
// - MetricsHelpMarker() [Internal]
18540
// - ShowFontAtlas() [Internal]
18541
// - ShowMetricsWindow()
18542
// - DebugNodeColumns() [Internal]
18543
// - DebugNodeDockNode() [Internal]
18544
// - DebugNodeDrawList() [Internal]
18545
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
18546
// - DebugNodeFont() [Internal]
18547
// - DebugNodeFontGlyph() [Internal]
18548
// - DebugNodeStorage() [Internal]
18549
// - DebugNodeTabBar() [Internal]
18550
// - DebugNodeViewport() [Internal]
18551
// - DebugNodeWindow() [Internal]
18552
// - DebugNodeWindowSettings() [Internal]
18553
// - DebugNodeWindowsList() [Internal]
18554
// - DebugNodeWindowsListByBeginStackParent() [Internal]
18555
//-----------------------------------------------------------------------------
18556
18557
#ifndef IMGUI_DISABLE_DEBUG_TOOLS
18558
18559
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
18560
0
{
18561
0
    ImGuiContext& g = *GImGui;
18562
0
    ImGuiWindow* window = g.CurrentWindow;
18563
18564
0
    ImVec2 scale = bb.GetSize() / viewport->Size;
18565
0
    ImVec2 off = bb.Min - viewport->Pos * scale;
18566
0
    float alpha_mul = (viewport->Flags & ImGuiViewportFlags_Minimized) ? 0.30f : 1.00f;
18567
0
    window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
18568
0
    for (int i = 0; i != g.Windows.Size; i++)
18569
0
    {
18570
0
        ImGuiWindow* thumb_window = g.Windows[i];
18571
0
        if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
18572
0
            continue;
18573
0
        if (thumb_window->Viewport != viewport)
18574
0
            continue;
18575
18576
0
        ImRect thumb_r = thumb_window->Rect();
18577
0
        ImRect title_r = thumb_window->TitleBarRect();
18578
0
        thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off +  thumb_r.Max * scale));
18579
0
        title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off +  ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
18580
0
        thumb_r.ClipWithFull(bb);
18581
0
        title_r.ClipWithFull(bb);
18582
0
        const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
18583
0
        window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
18584
0
        window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
18585
0
        window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18586
0
        window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
18587
0
    }
18588
0
    draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
18589
0
}
18590
18591
static void RenderViewportsThumbnails()
18592
0
{
18593
0
    ImGuiContext& g = *GImGui;
18594
0
    ImGuiWindow* window = g.CurrentWindow;
18595
18596
    // We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
18597
0
    float SCALE = 1.0f / 8.0f;
18598
0
    ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
18599
0
    for (int n = 0; n < g.Viewports.Size; n++)
18600
0
        bb_full.Add(g.Viewports[n]->GetMainRect());
18601
0
    ImVec2 p = window->DC.CursorPos;
18602
0
    ImVec2 off = p - bb_full.Min * SCALE;
18603
0
    for (int n = 0; n < g.Viewports.Size; n++)
18604
0
    {
18605
0
        ImGuiViewportP* viewport = g.Viewports[n];
18606
0
        ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
18607
0
        ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
18608
0
    }
18609
0
    ImGui::Dummy(bb_full.GetSize() * SCALE);
18610
0
}
18611
18612
static int IMGUI_CDECL ViewportComparerByFrontMostStampCount(const void* lhs, const void* rhs)
18613
0
{
18614
0
    const ImGuiViewportP* a = *(const ImGuiViewportP* const*)lhs;
18615
0
    const ImGuiViewportP* b = *(const ImGuiViewportP* const*)rhs;
18616
0
    return b->LastFrontMostStampCount - a->LastFrontMostStampCount;
18617
0
}
18618
18619
// Draw an arbitrary US keyboard layout to visualize translated keys
18620
void ImGui::DebugRenderKeyboardPreview(ImDrawList* draw_list)
18621
0
{
18622
0
    const ImVec2 key_size = ImVec2(35.0f, 35.0f);
18623
0
    const float  key_rounding = 3.0f;
18624
0
    const ImVec2 key_face_size = ImVec2(25.0f, 25.0f);
18625
0
    const ImVec2 key_face_pos = ImVec2(5.0f, 3.0f);
18626
0
    const float  key_face_rounding = 2.0f;
18627
0
    const ImVec2 key_label_pos = ImVec2(7.0f, 4.0f);
18628
0
    const ImVec2 key_step = ImVec2(key_size.x - 1.0f, key_size.y - 1.0f);
18629
0
    const float  key_row_offset = 9.0f;
18630
18631
0
    ImVec2 board_min = GetCursorScreenPos();
18632
0
    ImVec2 board_max = ImVec2(board_min.x + 3 * key_step.x + 2 * key_row_offset + 10.0f, board_min.y + 3 * key_step.y + 10.0f);
18633
0
    ImVec2 start_pos = ImVec2(board_min.x + 5.0f - key_step.x, board_min.y);
18634
18635
0
    struct KeyLayoutData { int Row, Col; const char* Label; ImGuiKey Key; };
18636
0
    const KeyLayoutData keys_to_display[] =
18637
0
    {
18638
0
        { 0, 0, "", ImGuiKey_Tab },      { 0, 1, "Q", ImGuiKey_Q }, { 0, 2, "W", ImGuiKey_W }, { 0, 3, "E", ImGuiKey_E }, { 0, 4, "R", ImGuiKey_R },
18639
0
        { 1, 0, "", ImGuiKey_CapsLock }, { 1, 1, "A", ImGuiKey_A }, { 1, 2, "S", ImGuiKey_S }, { 1, 3, "D", ImGuiKey_D }, { 1, 4, "F", ImGuiKey_F },
18640
0
        { 2, 0, "", ImGuiKey_LeftShift },{ 2, 1, "Z", ImGuiKey_Z }, { 2, 2, "X", ImGuiKey_X }, { 2, 3, "C", ImGuiKey_C }, { 2, 4, "V", ImGuiKey_V }
18641
0
    };
18642
18643
    // Elements rendered manually via ImDrawList API are not clipped automatically.
18644
    // While not strictly necessary, here IsItemVisible() is used to avoid rendering these shapes when they are out of view.
18645
0
    Dummy(board_max - board_min);
18646
0
    if (!IsItemVisible())
18647
0
        return;
18648
0
    draw_list->PushClipRect(board_min, board_max, true);
18649
0
    for (int n = 0; n < IM_ARRAYSIZE(keys_to_display); n++)
18650
0
    {
18651
0
        const KeyLayoutData* key_data = &keys_to_display[n];
18652
0
        ImVec2 key_min = ImVec2(start_pos.x + key_data->Col * key_step.x + key_data->Row * key_row_offset, start_pos.y + key_data->Row * key_step.y);
18653
0
        ImVec2 key_max = key_min + key_size;
18654
0
        draw_list->AddRectFilled(key_min, key_max, IM_COL32(204, 204, 204, 255), key_rounding);
18655
0
        draw_list->AddRect(key_min, key_max, IM_COL32(24, 24, 24, 255), key_rounding);
18656
0
        ImVec2 face_min = ImVec2(key_min.x + key_face_pos.x, key_min.y + key_face_pos.y);
18657
0
        ImVec2 face_max = ImVec2(face_min.x + key_face_size.x, face_min.y + key_face_size.y);
18658
0
        draw_list->AddRect(face_min, face_max, IM_COL32(193, 193, 193, 255), key_face_rounding, ImDrawFlags_None, 2.0f);
18659
0
        draw_list->AddRectFilled(face_min, face_max, IM_COL32(252, 252, 252, 255), key_face_rounding);
18660
0
        ImVec2 label_min = ImVec2(key_min.x + key_label_pos.x, key_min.y + key_label_pos.y);
18661
0
        draw_list->AddText(label_min, IM_COL32(64, 64, 64, 255), key_data->Label);
18662
0
        if (ImGui::IsKeyDown(key_data->Key))
18663
0
            draw_list->AddRectFilled(key_min, key_max, IM_COL32(255, 0, 0, 128), key_rounding);
18664
0
    }
18665
0
    draw_list->PopClipRect();
18666
0
}
18667
18668
// Helper tool to diagnose between text encoding issues and font loading issues. Pass your UTF-8 string and verify that there are correct.
18669
void ImGui::DebugTextEncoding(const char* str)
18670
0
{
18671
0
    Text("Text: \"%s\"", str);
18672
0
    if (!BeginTable("list", 4, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_SizingFixedFit))
18673
0
        return;
18674
0
    TableSetupColumn("Offset");
18675
0
    TableSetupColumn("UTF-8");
18676
0
    TableSetupColumn("Glyph");
18677
0
    TableSetupColumn("Codepoint");
18678
0
    TableHeadersRow();
18679
0
    for (const char* p = str; *p != 0; )
18680
0
    {
18681
0
        unsigned int c;
18682
0
        const int c_utf8_len = ImTextCharFromUtf8(&c, p, NULL);
18683
0
        TableNextColumn();
18684
0
        Text("%d", (int)(p - str));
18685
0
        TableNextColumn();
18686
0
        for (int byte_index = 0; byte_index < c_utf8_len; byte_index++)
18687
0
        {
18688
0
            if (byte_index > 0)
18689
0
                SameLine();
18690
0
            Text("0x%02X", (int)(unsigned char)p[byte_index]);
18691
0
        }
18692
0
        TableNextColumn();
18693
0
        if (GetFont()->FindGlyphNoFallback((ImWchar)c))
18694
0
            TextUnformatted(p, p + c_utf8_len);
18695
0
        else
18696
0
            TextUnformatted((c == IM_UNICODE_CODEPOINT_INVALID) ? "[invalid]" : "[missing]");
18697
0
        TableNextColumn();
18698
0
        Text("U+%04X", (int)c);
18699
0
        p += c_utf8_len;
18700
0
    }
18701
0
    EndTable();
18702
0
}
18703
18704
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
18705
static void MetricsHelpMarker(const char* desc)
18706
0
{
18707
0
    ImGui::TextDisabled("(?)");
18708
0
    if (ImGui::IsItemHovered(ImGuiHoveredFlags_DelayShort))
18709
0
    {
18710
0
        ImGui::BeginTooltip();
18711
0
        ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
18712
0
        ImGui::TextUnformatted(desc);
18713
0
        ImGui::PopTextWrapPos();
18714
0
        ImGui::EndTooltip();
18715
0
    }
18716
0
}
18717
18718
// [DEBUG] List fonts in a font atlas and display its texture
18719
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
18720
0
{
18721
0
    for (int i = 0; i < atlas->Fonts.Size; i++)
18722
0
    {
18723
0
        ImFont* font = atlas->Fonts[i];
18724
0
        PushID(font);
18725
0
        DebugNodeFont(font);
18726
0
        PopID();
18727
0
    }
18728
0
    if (TreeNode("Font Atlas", "Font Atlas (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
18729
0
    {
18730
0
        ImGuiContext& g = *GImGui;
18731
0
        ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18732
0
        Checkbox("Tint with Text Color", &cfg->ShowAtlasTintedWithTextColor); // Using text color ensure visibility of core atlas data, but will alter custom colored icons
18733
0
        ImVec4 tint_col = cfg->ShowAtlasTintedWithTextColor ? GetStyleColorVec4(ImGuiCol_Text) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
18734
0
        ImVec4 border_col = GetStyleColorVec4(ImGuiCol_Border);
18735
0
        Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
18736
0
        TreePop();
18737
0
    }
18738
0
}
18739
18740
void ImGui::ShowMetricsWindow(bool* p_open)
18741
0
{
18742
0
    ImGuiContext& g = *GImGui;
18743
0
    ImGuiIO& io = g.IO;
18744
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
18745
0
    if (cfg->ShowDebugLog)
18746
0
        ShowDebugLogWindow(&cfg->ShowDebugLog);
18747
0
    if (cfg->ShowStackTool)
18748
0
        ShowStackToolWindow(&cfg->ShowStackTool);
18749
18750
0
    if (!Begin("Dear ImGui Metrics/Debugger", p_open) || GetCurrentWindow()->BeginCount > 1)
18751
0
    {
18752
0
        End();
18753
0
        return;
18754
0
    }
18755
18756
    // Basic info
18757
0
    Text("Dear ImGui %s", GetVersion());
18758
0
    Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
18759
0
    Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
18760
0
    Text("%d visible windows, %d active allocations", io.MetricsRenderWindows, io.MetricsActiveAllocations);
18761
    //SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
18762
18763
0
    Separator();
18764
18765
    // Debugging enums
18766
0
    enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
18767
0
    const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
18768
0
    enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
18769
0
    const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
18770
0
    if (cfg->ShowWindowsRectsType < 0)
18771
0
        cfg->ShowWindowsRectsType = WRT_WorkRect;
18772
0
    if (cfg->ShowTablesRectsType < 0)
18773
0
        cfg->ShowTablesRectsType = TRT_WorkRect;
18774
18775
0
    struct Funcs
18776
0
    {
18777
0
        static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
18778
0
        {
18779
0
            ImGuiTableInstanceData* table_instance = TableGetInstanceData(table, table->InstanceCurrent); // Always using last submitted instance
18780
0
            if (rect_type == TRT_OuterRect)                     { return table->OuterRect; }
18781
0
            else if (rect_type == TRT_InnerRect)                { return table->InnerRect; }
18782
0
            else if (rect_type == TRT_WorkRect)                 { return table->WorkRect; }
18783
0
            else if (rect_type == TRT_HostClipRect)             { return table->HostClipRect; }
18784
0
            else if (rect_type == TRT_InnerClipRect)            { return table->InnerClipRect; }
18785
0
            else if (rect_type == TRT_BackgroundClipRect)       { return table->BgClipRect; }
18786
0
            else if (rect_type == TRT_ColumnsRect)              { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table_instance->LastOuterHeight); }
18787
0
            else if (rect_type == TRT_ColumnsWorkRect)          { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
18788
0
            else if (rect_type == TRT_ColumnsClipRect)          { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
18789
0
            else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); } // Note: y1/y2 not always accurate
18790
0
            else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table_instance->LastFirstRowHeight); }
18791
0
            else if (rect_type == TRT_ColumnsContentFrozen)     { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight); }
18792
0
            else if (rect_type == TRT_ColumnsContentUnfrozen)   { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table_instance->LastFrozenHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
18793
0
            IM_ASSERT(0);
18794
0
            return ImRect();
18795
0
        }
18796
18797
0
        static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
18798
0
        {
18799
0
            if (rect_type == WRT_OuterRect)                 { return window->Rect(); }
18800
0
            else if (rect_type == WRT_OuterRectClipped)     { return window->OuterRectClipped; }
18801
0
            else if (rect_type == WRT_InnerRect)            { return window->InnerRect; }
18802
0
            else if (rect_type == WRT_InnerClipRect)        { return window->InnerClipRect; }
18803
0
            else if (rect_type == WRT_WorkRect)             { return window->WorkRect; }
18804
0
            else if (rect_type == WRT_Content)       { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
18805
0
            else if (rect_type == WRT_ContentIdeal)         { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
18806
0
            else if (rect_type == WRT_ContentRegionRect)    { return window->ContentRegionRect; }
18807
0
            IM_ASSERT(0);
18808
0
            return ImRect();
18809
0
        }
18810
0
    };
18811
18812
    // Tools
18813
0
    if (TreeNode("Tools"))
18814
0
    {
18815
0
        bool show_encoding_viewer = TreeNode("UTF-8 Encoding viewer");
18816
0
        SameLine();
18817
0
        MetricsHelpMarker("You can also call ImGui::DebugTextEncoding() from your code with a given string to test that your UTF-8 encoding settings are correct.");
18818
0
        if (show_encoding_viewer)
18819
0
        {
18820
0
            static char buf[100] = "";
18821
0
            SetNextItemWidth(-FLT_MIN);
18822
0
            InputText("##Text", buf, IM_ARRAYSIZE(buf));
18823
0
            if (buf[0] != 0)
18824
0
                DebugTextEncoding(buf);
18825
0
            TreePop();
18826
0
        }
18827
18828
        // The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
18829
0
        if (Checkbox("Show Item Picker", &g.DebugItemPickerActive) && g.DebugItemPickerActive)
18830
0
            DebugStartItemPicker();
18831
0
        SameLine();
18832
0
        MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
18833
18834
        // Stack Tool is your best friend!
18835
0
        Checkbox("Show Debug Log", &cfg->ShowDebugLog);
18836
0
        SameLine();
18837
0
        MetricsHelpMarker("You can also call ImGui::ShowDebugLogWindow() from your code.");
18838
18839
        // Stack Tool is your best friend!
18840
0
        Checkbox("Show Stack Tool", &cfg->ShowStackTool);
18841
0
        SameLine();
18842
0
        MetricsHelpMarker("You can also call ImGui::ShowStackToolWindow() from your code.");
18843
18844
0
        Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
18845
0
        Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
18846
0
        SameLine();
18847
0
        SetNextItemWidth(GetFontSize() * 12);
18848
0
        cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
18849
0
        if (cfg->ShowWindowsRects && g.NavWindow != NULL)
18850
0
        {
18851
0
            BulletText("'%s':", g.NavWindow->Name);
18852
0
            Indent();
18853
0
            for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
18854
0
            {
18855
0
                ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
18856
0
                Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
18857
0
            }
18858
0
            Unindent();
18859
0
        }
18860
18861
0
        Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
18862
0
        SameLine();
18863
0
        SetNextItemWidth(GetFontSize() * 12);
18864
0
        cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
18865
0
        if (cfg->ShowTablesRects && g.NavWindow != NULL)
18866
0
        {
18867
0
            for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
18868
0
            {
18869
0
                ImGuiTable* table = g.Tables.TryGetMapData(table_n);
18870
0
                if (table == NULL || table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
18871
0
                    continue;
18872
18873
0
                BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
18874
0
                if (IsItemHovered())
18875
0
                    GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18876
0
                Indent();
18877
0
                char buf[128];
18878
0
                for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
18879
0
                {
18880
0
                    if (rect_n >= TRT_ColumnsRect)
18881
0
                    {
18882
0
                        if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
18883
0
                            continue;
18884
0
                        for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
18885
0
                        {
18886
0
                            ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
18887
0
                            ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
18888
0
                            Selectable(buf);
18889
0
                            if (IsItemHovered())
18890
0
                                GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18891
0
                        }
18892
0
                    }
18893
0
                    else
18894
0
                    {
18895
0
                        ImRect r = Funcs::GetTableRect(table, rect_n, -1);
18896
0
                        ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
18897
0
                        Selectable(buf);
18898
0
                        if (IsItemHovered())
18899
0
                            GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
18900
0
                    }
18901
0
                }
18902
0
                Unindent();
18903
0
            }
18904
0
        }
18905
18906
0
        TreePop();
18907
0
    }
18908
18909
    // Windows
18910
0
    if (TreeNode("Windows", "Windows (%d)", g.Windows.Size))
18911
0
    {
18912
        //SetNextItemOpen(true, ImGuiCond_Once);
18913
0
        DebugNodeWindowsList(&g.Windows, "By display order");
18914
0
        DebugNodeWindowsList(&g.WindowsFocusOrder, "By focus order (root windows)");
18915
0
        if (TreeNode("By submission order (begin stack)"))
18916
0
        {
18917
            // Here we display windows in their submitted order/hierarchy, however note that the Begin stack doesn't constitute a Parent<>Child relationship!
18918
0
            ImVector<ImGuiWindow*>& temp_buffer = g.WindowsTempSortBuffer;
18919
0
            temp_buffer.resize(0);
18920
0
            for (int i = 0; i < g.Windows.Size; i++)
18921
0
                if (g.Windows[i]->LastFrameActive + 1 >= g.FrameCount)
18922
0
                    temp_buffer.push_back(g.Windows[i]);
18923
0
            struct Func { static int IMGUI_CDECL WindowComparerByBeginOrder(const void* lhs, const void* rhs) { return ((int)(*(const ImGuiWindow* const *)lhs)->BeginOrderWithinContext - (*(const ImGuiWindow* const*)rhs)->BeginOrderWithinContext); } };
18924
0
            ImQsort(temp_buffer.Data, (size_t)temp_buffer.Size, sizeof(ImGuiWindow*), Func::WindowComparerByBeginOrder);
18925
0
            DebugNodeWindowsListByBeginStackParent(temp_buffer.Data, temp_buffer.Size, NULL);
18926
0
            TreePop();
18927
0
        }
18928
18929
0
        TreePop();
18930
0
    }
18931
18932
    // DrawLists
18933
0
    int drawlist_count = 0;
18934
0
    for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18935
0
        drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
18936
0
    if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
18937
0
    {
18938
0
        Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
18939
0
        Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
18940
0
        for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
18941
0
        {
18942
0
            ImGuiViewportP* viewport = g.Viewports[viewport_i];
18943
0
            bool viewport_has_drawlist = false;
18944
0
            for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
18945
0
                for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
18946
0
                {
18947
0
                    if (!viewport_has_drawlist)
18948
0
                        Text("Active DrawLists in Viewport #%d, ID: 0x%08X", viewport->Idx, viewport->ID);
18949
0
                    viewport_has_drawlist = true;
18950
0
                    DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
18951
0
                }
18952
0
        }
18953
0
        TreePop();
18954
0
    }
18955
18956
    // Viewports
18957
0
    if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
18958
0
    {
18959
0
        Indent(GetTreeNodeToLabelSpacing());
18960
0
        RenderViewportsThumbnails();
18961
0
        Unindent(GetTreeNodeToLabelSpacing());
18962
18963
0
        bool open = TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size);
18964
0
        SameLine();
18965
0
        MetricsHelpMarker("Dear ImGui uses monitor data:\n- to query DPI settings on a per monitor basis\n- to position popup/tooltips so they don't straddle monitors.");
18966
0
        if (open)
18967
0
        {
18968
0
            for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
18969
0
            {
18970
0
                const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
18971
0
                BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
18972
0
                    i, mon.DpiScale * 100.0f,
18973
0
                    mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
18974
0
                    mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
18975
0
            }
18976
0
            TreePop();
18977
0
        }
18978
18979
0
        BulletText("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport ? g.MouseViewport->ID : 0, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
18980
0
        if (TreeNode("Inferred Z order (front-to-back)"))
18981
0
        {
18982
0
            static ImVector<ImGuiViewportP*> viewports;
18983
0
            viewports.resize(g.Viewports.Size);
18984
0
            memcpy(viewports.Data, g.Viewports.Data, g.Viewports.size_in_bytes());
18985
0
            if (viewports.Size > 1)
18986
0
                ImQsort(viewports.Data, viewports.Size, sizeof(ImGuiViewport*), ViewportComparerByFrontMostStampCount);
18987
0
            for (int i = 0; i < viewports.Size; i++)
18988
0
                BulletText("Viewport #%d, ID: 0x%08X, FrontMostStampCount = %08d, Window: \"%s\"", viewports[i]->Idx, viewports[i]->ID, viewports[i]->LastFrontMostStampCount, viewports[i]->Window ? viewports[i]->Window->Name : "N/A");
18989
0
            TreePop();
18990
0
        }
18991
18992
0
        for (int i = 0; i < g.Viewports.Size; i++)
18993
0
            DebugNodeViewport(g.Viewports[i]);
18994
0
        TreePop();
18995
0
    }
18996
18997
    // Details for Popups
18998
0
    if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
18999
0
    {
19000
0
        for (int i = 0; i < g.OpenPopupStack.Size; i++)
19001
0
        {
19002
            // As it's difficult to interact with tree nodes while popups are open, we display everything inline.
19003
0
            const ImGuiPopupData* popup_data = &g.OpenPopupStack[i];
19004
0
            ImGuiWindow* window = popup_data->Window;
19005
0
            BulletText("PopupID: %08x, Window: '%s' (%s%s), BackupNavWindow '%s', ParentWindow '%s'",
19006
0
                popup_data->PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? "Child;" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? "Menu;" : "",
19007
0
                popup_data->BackupNavWindow ? popup_data->BackupNavWindow->Name : "NULL", window && window->ParentWindow ? window->ParentWindow->Name : "NULL");
19008
0
        }
19009
0
        TreePop();
19010
0
    }
19011
19012
    // Details for TabBars
19013
0
    if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetAliveCount()))
19014
0
    {
19015
0
        for (int n = 0; n < g.TabBars.GetMapSize(); n++)
19016
0
            if (ImGuiTabBar* tab_bar = g.TabBars.TryGetMapData(n))
19017
0
            {
19018
0
                PushID(tab_bar);
19019
0
                DebugNodeTabBar(tab_bar, "TabBar");
19020
0
                PopID();
19021
0
            }
19022
0
        TreePop();
19023
0
    }
19024
19025
    // Details for Tables
19026
0
    if (TreeNode("Tables", "Tables (%d)", g.Tables.GetAliveCount()))
19027
0
    {
19028
0
        for (int n = 0; n < g.Tables.GetMapSize(); n++)
19029
0
            if (ImGuiTable* table = g.Tables.TryGetMapData(n))
19030
0
                DebugNodeTable(table);
19031
0
        TreePop();
19032
0
    }
19033
19034
    // Details for Fonts
19035
0
    ImFontAtlas* atlas = g.IO.Fonts;
19036
0
    if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
19037
0
    {
19038
0
        ShowFontAtlas(atlas);
19039
0
        TreePop();
19040
0
    }
19041
19042
    // Details for InputText
19043
0
    if (TreeNode("InputText"))
19044
0
    {
19045
0
        DebugNodeInputTextState(&g.InputTextState);
19046
0
        TreePop();
19047
0
    }
19048
19049
    // Details for Docking
19050
0
#ifdef IMGUI_HAS_DOCK
19051
0
    if (TreeNode("Docking"))
19052
0
    {
19053
0
        static bool root_nodes_only = true;
19054
0
        ImGuiDockContext* dc = &g.DockContext;
19055
0
        Checkbox("List root nodes", &root_nodes_only);
19056
0
        Checkbox("Ctrl shows window dock info", &cfg->ShowDockingNodes);
19057
0
        if (SmallButton("Clear nodes")) { DockContextClearNodes(&g, 0, true); }
19058
0
        SameLine();
19059
0
        if (SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
19060
0
        for (int n = 0; n < dc->Nodes.Data.Size; n++)
19061
0
            if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
19062
0
                if (!root_nodes_only || node->IsRootNode())
19063
0
                    DebugNodeDockNode(node, "Node");
19064
0
        TreePop();
19065
0
    }
19066
0
#endif // #ifdef IMGUI_HAS_DOCK
19067
19068
    // Settings
19069
0
    if (TreeNode("Settings"))
19070
0
    {
19071
0
        if (SmallButton("Clear"))
19072
0
            ClearIniSettings();
19073
0
        SameLine();
19074
0
        if (SmallButton("Save to memory"))
19075
0
            SaveIniSettingsToMemory();
19076
0
        SameLine();
19077
0
        if (SmallButton("Save to disk"))
19078
0
            SaveIniSettingsToDisk(g.IO.IniFilename);
19079
0
        SameLine();
19080
0
        if (g.IO.IniFilename)
19081
0
            Text("\"%s\"", g.IO.IniFilename);
19082
0
        else
19083
0
            TextUnformatted("<NULL>");
19084
0
        Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
19085
0
        if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
19086
0
        {
19087
0
            for (int n = 0; n < g.SettingsHandlers.Size; n++)
19088
0
                BulletText("%s", g.SettingsHandlers[n].TypeName);
19089
0
            TreePop();
19090
0
        }
19091
0
        if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
19092
0
        {
19093
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19094
0
                DebugNodeWindowSettings(settings);
19095
0
            TreePop();
19096
0
        }
19097
19098
0
        if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
19099
0
        {
19100
0
            for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
19101
0
                DebugNodeTableSettings(settings);
19102
0
            TreePop();
19103
0
        }
19104
19105
0
#ifdef IMGUI_HAS_DOCK
19106
0
        if (TreeNode("SettingsDocking", "Settings packed data: Docking"))
19107
0
        {
19108
0
            ImGuiDockContext* dc = &g.DockContext;
19109
0
            Text("In SettingsWindows:");
19110
0
            for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
19111
0
                if (settings->DockId != 0)
19112
0
                    BulletText("Window '%s' -> DockId %08X", settings->GetName(), settings->DockId);
19113
0
            Text("In SettingsNodes:");
19114
0
            for (int n = 0; n < dc->NodesSettings.Size; n++)
19115
0
            {
19116
0
                ImGuiDockNodeSettings* settings = &dc->NodesSettings[n];
19117
0
                const char* selected_tab_name = NULL;
19118
0
                if (settings->SelectedTabId)
19119
0
                {
19120
0
                    if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabId))
19121
0
                        selected_tab_name = window->Name;
19122
0
                    else if (ImGuiWindowSettings* window_settings = FindWindowSettingsByID(settings->SelectedTabId))
19123
0
                        selected_tab_name = window_settings->GetName();
19124
0
                }
19125
0
                BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentNodeId, settings->SelectedTabId, selected_tab_name ? selected_tab_name : settings->SelectedTabId ? "N/A" : "");
19126
0
            }
19127
0
            TreePop();
19128
0
        }
19129
0
#endif // #ifdef IMGUI_HAS_DOCK
19130
19131
0
        if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
19132
0
        {
19133
0
            InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
19134
0
            TreePop();
19135
0
        }
19136
0
        TreePop();
19137
0
    }
19138
19139
0
    if (TreeNode("Inputs"))
19140
0
    {
19141
0
        Text("KEYBOARD/GAMEPAD/MOUSE KEYS");
19142
0
        {
19143
            // We iterate both legacy native range and named ImGuiKey ranges, which is a little odd but this allows displaying the data for old/new backends.
19144
            // User code should never have to go through such hoops: old code may use native keycodes, new code may use ImGuiKey codes.
19145
0
            Indent();
19146
0
#ifdef IMGUI_DISABLE_OBSOLETE_KEYIO
19147
0
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey) { return false; } };
19148
#else
19149
            struct funcs { static bool IsLegacyNativeDupe(ImGuiKey key) { return key < 512 && GetIO().KeyMap[key] != -1; } }; // Hide Native<>ImGuiKey duplicates when both exists in the array
19150
            //Text("Legacy raw:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key++) { if (io.KeysDown[key]) { SameLine(); Text("\"%s\" %d", GetKeyName(key), key); } }
19151
#endif
19152
0
            Text("Keys down:");         for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyDown(key)) continue;     SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); SameLine(); Text("(%.02f)", GetKeyData(key)->DownDuration); }
19153
0
            Text("Keys pressed:");      for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyPressed(key)) continue;  SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19154
0
            Text("Keys released:");     for (ImGuiKey key = ImGuiKey_KeysData_OFFSET; key < ImGuiKey_COUNT; key = (ImGuiKey)(key + 1)) { if (funcs::IsLegacyNativeDupe(key) || !IsKeyReleased(key)) continue; SameLine(); Text(IsNamedKey(key) ? "\"%s\"" : "\"%s\" %d", GetKeyName(key), key); }
19155
0
            Text("Keys mods: %s%s%s%s", io.KeyCtrl ? "CTRL " : "", io.KeyShift ? "SHIFT " : "", io.KeyAlt ? "ALT " : "", io.KeySuper ? "SUPER " : "");
19156
0
            Text("Chars queue:");       for (int i = 0; i < io.InputQueueCharacters.Size; i++) { ImWchar c = io.InputQueueCharacters[i]; SameLine(); Text("\'%c\' (0x%04X)", (c > ' ' && c <= 255) ? (char)c : '?', c); } // FIXME: We should convert 'c' to UTF-8 here but the functions are not public.
19157
0
            DebugRenderKeyboardPreview(GetWindowDrawList());
19158
0
            Unindent();
19159
0
        }
19160
19161
0
        Text("MOUSE STATE");
19162
0
        {
19163
0
            Indent();
19164
0
            if (IsMousePosValid())
19165
0
                Text("Mouse pos: (%g, %g)", io.MousePos.x, io.MousePos.y);
19166
0
            else
19167
0
                Text("Mouse pos: <INVALID>");
19168
0
            Text("Mouse delta: (%g, %g)", io.MouseDelta.x, io.MouseDelta.y);
19169
0
            int count = IM_ARRAYSIZE(io.MouseDown);
19170
0
            Text("Mouse down:");     for (int i = 0; i < count; i++) if (IsMouseDown(i)) { SameLine(); Text("b%d (%.02f secs)", i, io.MouseDownDuration[i]); }
19171
0
            Text("Mouse clicked:");  for (int i = 0; i < count; i++) if (IsMouseClicked(i)) { SameLine(); Text("b%d (%d)", i, io.MouseClickedCount[i]); }
19172
0
            Text("Mouse released:"); for (int i = 0; i < count; i++) if (IsMouseReleased(i)) { SameLine(); Text("b%d", i); }
19173
0
            Text("Mouse wheel: %.1f", io.MouseWheel);
19174
0
            Text("Pen Pressure: %.1f", io.PenPressure); // Note: currently unused
19175
0
            Unindent();
19176
0
        }
19177
19178
0
        Text("MOUSE WHEELING");
19179
0
        {
19180
0
            Indent();
19181
0
            Text("WheelingWindow: '%s'", g.WheelingWindow ? g.WheelingWindow->Name : "NULL");
19182
0
            Text("WheelingWindowReleaseTimer: %.2f", g.WheelingWindowReleaseTimer);
19183
0
            Text("WheelingAxisAvg[] = { %.3f, %.3f }, Main Axis: %s", g.WheelingAxisAvg.x, g.WheelingAxisAvg.y, (g.WheelingAxisAvg.x > g.WheelingAxisAvg.y) ? "X" : (g.WheelingAxisAvg.x < g.WheelingAxisAvg.y) ? "Y" : "<none>");
19184
0
            Unindent();
19185
0
        }
19186
19187
0
        Text("KEY OWNERS");
19188
0
        {
19189
0
            Indent();
19190
0
            if (BeginListBox("##owners", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19191
0
            {
19192
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19193
0
                {
19194
0
                    ImGuiKeyOwnerData* owner_data = GetKeyOwnerData(key);
19195
0
                    if (owner_data->OwnerCurr == ImGuiKeyOwner_None)
19196
0
                        continue;
19197
0
                    Text("%s: 0x%08X%s", GetKeyName(key), owner_data->OwnerCurr,
19198
0
                        owner_data->LockUntilRelease ? " LockUntilRelease" : owner_data->LockThisFrame ? " LockThisFrame" : "");
19199
0
                    DebugLocateItemOnHover(owner_data->OwnerCurr);
19200
0
                }
19201
0
                EndListBox();
19202
0
            }
19203
0
            Unindent();
19204
0
        }
19205
0
        Text("SHORTCUT ROUTING");
19206
0
        {
19207
0
            Indent();
19208
0
            if (BeginListBox("##routes", ImVec2(-FLT_MIN, GetTextLineHeightWithSpacing() * 6)))
19209
0
            {
19210
0
                for (ImGuiKey key = ImGuiKey_NamedKey_BEGIN; key < ImGuiKey_NamedKey_END; key = (ImGuiKey)(key + 1))
19211
0
                {
19212
0
                    ImGuiKeyRoutingTable* rt = &g.KeysRoutingTable;
19213
0
                    for (ImGuiKeyRoutingIndex idx = rt->Index[key - ImGuiKey_NamedKey_BEGIN]; idx != -1; )
19214
0
                    {
19215
0
                        char key_chord_name[64];
19216
0
                        ImGuiKeyRoutingData* routing_data = &rt->Entries[idx];
19217
0
                        GetKeyChordName(key | routing_data->Mods, key_chord_name, IM_ARRAYSIZE(key_chord_name));
19218
0
                        Text("%s: 0x%08X", key_chord_name, routing_data->RoutingCurr);
19219
0
                        DebugLocateItemOnHover(routing_data->RoutingCurr);
19220
0
                        idx = routing_data->NextEntryIndex;
19221
0
                    }
19222
0
                }
19223
0
                EndListBox();
19224
0
            }
19225
0
            Text("(ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: 0x%X)", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19226
0
            Unindent();
19227
0
        }
19228
0
        TreePop();
19229
0
    }
19230
19231
0
    if (TreeNode("Internal state"))
19232
0
    {
19233
0
        Text("WINDOWING");
19234
0
        Indent();
19235
0
        Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
19236
0
        Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindowDockTree->Name : "NULL");
19237
0
        Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
19238
0
        Text("HoveredDockNode: 0x%08X", g.DebugHoveredDockNode ? g.DebugHoveredDockNode->ID : 0);
19239
0
        Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
19240
0
        Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
19241
0
        Unindent();
19242
19243
0
        Text("ITEMS");
19244
0
        Indent();
19245
0
        Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, GetInputSourceName(g.ActiveIdSource));
19246
0
        DebugLocateItemOnHover(g.ActiveId);
19247
0
        Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
19248
0
        Text("ActiveIdUsing: AllKeyboardKeys: %d, NavDirMask: %X", g.ActiveIdUsingAllKeyboardKeys, g.ActiveIdUsingNavDirMask);
19249
0
        Text("HoveredId: 0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Not displaying g.HoveredId as it is update mid-frame
19250
0
        Text("HoverDelayId: 0x%08X, Timer: %.2f, ClearTimer: %.2f", g.HoverDelayId, g.HoverDelayTimer, g.HoverDelayClearTimer);
19251
0
        Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
19252
0
        DebugLocateItemOnHover(g.DragDropPayload.SourceId);
19253
0
        Unindent();
19254
19255
0
        Text("NAV,FOCUS");
19256
0
        Indent();
19257
0
        Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
19258
0
        Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
19259
0
        DebugLocateItemOnHover(g.NavId);
19260
0
        Text("NavInputSource: %s", GetInputSourceName(g.NavInputSource));
19261
0
        Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
19262
0
        Text("NavActivateId/DownId/PressedId/InputId: %08X/%08X/%08X/%08X", g.NavActivateId, g.NavActivateDownId, g.NavActivatePressedId, g.NavActivateInputId);
19263
0
        Text("NavActivateFlags: %04X", g.NavActivateFlags);
19264
0
        Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
19265
0
        Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
19266
0
        Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
19267
0
        Unindent();
19268
19269
0
        TreePop();
19270
0
    }
19271
19272
    // Overlay: Display windows Rectangles and Begin Order
19273
0
    if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
19274
0
    {
19275
0
        for (int n = 0; n < g.Windows.Size; n++)
19276
0
        {
19277
0
            ImGuiWindow* window = g.Windows[n];
19278
0
            if (!window->WasActive)
19279
0
                continue;
19280
0
            ImDrawList* draw_list = GetForegroundDrawList(window);
19281
0
            if (cfg->ShowWindowsRects)
19282
0
            {
19283
0
                ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
19284
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19285
0
            }
19286
0
            if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
19287
0
            {
19288
0
                char buf[32];
19289
0
                ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
19290
0
                float font_size = GetFontSize();
19291
0
                draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
19292
0
                draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
19293
0
            }
19294
0
        }
19295
0
    }
19296
19297
    // Overlay: Display Tables Rectangles
19298
0
    if (cfg->ShowTablesRects)
19299
0
    {
19300
0
        for (int table_n = 0; table_n < g.Tables.GetMapSize(); table_n++)
19301
0
        {
19302
0
            ImGuiTable* table = g.Tables.TryGetMapData(table_n);
19303
0
            if (table == NULL || table->LastFrameActive < g.FrameCount - 1)
19304
0
                continue;
19305
0
            ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
19306
0
            if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
19307
0
            {
19308
0
                for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
19309
0
                {
19310
0
                    ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
19311
0
                    ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
19312
0
                    float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
19313
0
                    draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
19314
0
                }
19315
0
            }
19316
0
            else
19317
0
            {
19318
0
                ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
19319
0
                draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
19320
0
            }
19321
0
        }
19322
0
    }
19323
19324
0
#ifdef IMGUI_HAS_DOCK
19325
    // Overlay: Display Docking info
19326
0
    if (cfg->ShowDockingNodes && g.IO.KeyCtrl && g.DebugHoveredDockNode)
19327
0
    {
19328
0
        char buf[64] = "";
19329
0
        char* p = buf;
19330
0
        ImGuiDockNode* node = g.DebugHoveredDockNode;
19331
0
        ImDrawList* overlay_draw_list = node->HostWindow ? GetForegroundDrawList(node->HostWindow) : GetForegroundDrawList(GetMainViewport());
19332
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode() ? " *CentralNode*" : "");
19333
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "WindowClass: %08X\n", node->WindowClass.ClassId);
19334
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
19335
0
        p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
19336
0
        int depth = DockNodeGetDepth(node);
19337
0
        overlay_draw_list->AddRect(node->Pos + ImVec2(3, 3) * (float)depth, node->Pos + node->Size - ImVec2(3, 3) * (float)depth, IM_COL32(200, 100, 100, 255));
19338
0
        ImVec2 pos = node->Pos + ImVec2(3, 3) * (float)depth;
19339
0
        overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
19340
0
        overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
19341
0
    }
19342
0
#endif // #ifdef IMGUI_HAS_DOCK
19343
19344
0
    End();
19345
0
}
19346
19347
// [DEBUG] Display contents of Columns
19348
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
19349
0
{
19350
0
    if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
19351
0
        return;
19352
0
    BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
19353
0
    for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
19354
0
        BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
19355
0
    TreePop();
19356
0
}
19357
19358
static void DebugNodeDockNodeFlags(ImGuiDockNodeFlags* p_flags, const char* label, bool enabled)
19359
0
{
19360
0
    using namespace ImGui;
19361
0
    PushID(label);
19362
0
    PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0.0f, 0.0f));
19363
0
    Text("%s:", label);
19364
0
    if (!enabled)
19365
0
        BeginDisabled();
19366
0
    CheckboxFlags("NoSplit", p_flags, ImGuiDockNodeFlags_NoSplit);
19367
0
    CheckboxFlags("NoResize", p_flags, ImGuiDockNodeFlags_NoResize);
19368
0
    CheckboxFlags("NoResizeX", p_flags, ImGuiDockNodeFlags_NoResizeX);
19369
0
    CheckboxFlags("NoResizeY",p_flags, ImGuiDockNodeFlags_NoResizeY);
19370
0
    CheckboxFlags("NoTabBar", p_flags, ImGuiDockNodeFlags_NoTabBar);
19371
0
    CheckboxFlags("HiddenTabBar", p_flags, ImGuiDockNodeFlags_HiddenTabBar);
19372
0
    CheckboxFlags("NoWindowMenuButton", p_flags, ImGuiDockNodeFlags_NoWindowMenuButton);
19373
0
    CheckboxFlags("NoCloseButton", p_flags, ImGuiDockNodeFlags_NoCloseButton);
19374
0
    CheckboxFlags("NoDocking", p_flags, ImGuiDockNodeFlags_NoDocking);
19375
0
    CheckboxFlags("NoDockingSplitMe", p_flags, ImGuiDockNodeFlags_NoDockingSplitMe);
19376
0
    CheckboxFlags("NoDockingSplitOther", p_flags, ImGuiDockNodeFlags_NoDockingSplitOther);
19377
0
    CheckboxFlags("NoDockingOverMe", p_flags, ImGuiDockNodeFlags_NoDockingOverMe);
19378
0
    CheckboxFlags("NoDockingOverOther", p_flags, ImGuiDockNodeFlags_NoDockingOverOther);
19379
0
    CheckboxFlags("NoDockingOverEmpty", p_flags, ImGuiDockNodeFlags_NoDockingOverEmpty);
19380
0
    if (!enabled)
19381
0
        EndDisabled();
19382
0
    PopStyleVar();
19383
0
    PopID();
19384
0
}
19385
19386
// [DEBUG] Display contents of ImDockNode
19387
void ImGui::DebugNodeDockNode(ImGuiDockNode* node, const char* label)
19388
0
{
19389
0
    ImGuiContext& g = *GImGui;
19390
0
    const bool is_alive = (g.FrameCount - node->LastFrameAlive < 2);    // Submitted with ImGuiDockNodeFlags_KeepAliveOnly
19391
0
    const bool is_active = (g.FrameCount - node->LastFrameActive < 2);  // Submitted
19392
0
    if (!is_alive) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19393
0
    bool open;
19394
0
    ImGuiTreeNodeFlags tree_node_flags = node->IsFocused ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19395
0
    if (node->Windows.Size > 0)
19396
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19397
0
    else
19398
0
        open = TreeNodeEx((void*)(intptr_t)node->ID, tree_node_flags, "%s 0x%04X%s: %s (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal split" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical split" : "empty", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
19399
0
    if (!is_alive) { PopStyleColor(); }
19400
0
    if (is_active && IsItemHovered())
19401
0
        if (ImGuiWindow* window = node->HostWindow ? node->HostWindow : node->VisibleWindow)
19402
0
            GetForegroundDrawList(window)->AddRect(node->Pos, node->Pos + node->Size, IM_COL32(255, 255, 0, 255));
19403
0
    if (open)
19404
0
    {
19405
0
        IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
19406
0
        IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
19407
0
        BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
19408
0
            node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
19409
0
        DebugNodeWindow(node->HostWindow, "HostWindow");
19410
0
        DebugNodeWindow(node->VisibleWindow, "VisibleWindow");
19411
0
        BulletText("SelectedTabID: 0x%08X, LastFocusedNodeID: 0x%08X", node->SelectedTabId, node->LastFocusedNodeId);
19412
0
        BulletText("Misc:%s%s%s%s%s%s%s",
19413
0
            node->IsDockSpace() ? " IsDockSpace" : "",
19414
0
            node->IsCentralNode() ? " IsCentralNode" : "",
19415
0
            is_alive ? " IsAlive" : "", is_active ? " IsActive" : "", node->IsFocused ? " IsFocused" : "",
19416
0
            node->WantLockSizeOnce ? " WantLockSizeOnce" : "",
19417
0
            node->HasCentralNodeChild ? " HasCentralNodeChild" : "");
19418
0
        if (TreeNode("flags", "Flags Merged: 0x%04X, Local: 0x%04X, InWindows: 0x%04X, Shared: 0x%04X", node->MergedFlags, node->LocalFlags, node->LocalFlagsInWindows, node->SharedFlags))
19419
0
        {
19420
0
            if (BeginTable("flags", 4))
19421
0
            {
19422
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->MergedFlags, "MergedFlags", false);
19423
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlags, "LocalFlags", true);
19424
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->LocalFlagsInWindows, "LocalFlagsInWindows", false);
19425
0
                TableNextColumn(); DebugNodeDockNodeFlags(&node->SharedFlags, "SharedFlags", true);
19426
0
                EndTable();
19427
0
            }
19428
0
            TreePop();
19429
0
        }
19430
0
        if (node->ParentNode)
19431
0
            DebugNodeDockNode(node->ParentNode, "ParentNode");
19432
0
        if (node->ChildNodes[0])
19433
0
            DebugNodeDockNode(node->ChildNodes[0], "Child[0]");
19434
0
        if (node->ChildNodes[1])
19435
0
            DebugNodeDockNode(node->ChildNodes[1], "Child[1]");
19436
0
        if (node->TabBar)
19437
0
            DebugNodeTabBar(node->TabBar, "TabBar");
19438
0
        DebugNodeWindowsList(&node->Windows, "Windows");
19439
19440
0
        TreePop();
19441
0
    }
19442
0
}
19443
19444
// [DEBUG] Display contents of ImDrawList
19445
// Note that both 'window' and 'viewport' may be NULL here. Viewport is generally null of destroyed popups which previously owned a viewport.
19446
void ImGui::DebugNodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, const ImDrawList* draw_list, const char* label)
19447
0
{
19448
0
    ImGuiContext& g = *GImGui;
19449
0
    ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
19450
0
    int cmd_count = draw_list->CmdBuffer.Size;
19451
0
    if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
19452
0
        cmd_count--;
19453
0
    bool node_open = TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, cmd_count);
19454
0
    if (draw_list == GetWindowDrawList())
19455
0
    {
19456
0
        SameLine();
19457
0
        TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
19458
0
        if (node_open)
19459
0
            TreePop();
19460
0
        return;
19461
0
    }
19462
19463
0
    ImDrawList* fg_draw_list = viewport ? GetForegroundDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
19464
0
    if (window && IsItemHovered() && fg_draw_list)
19465
0
        fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19466
0
    if (!node_open)
19467
0
        return;
19468
19469
0
    if (window && !window->WasActive)
19470
0
        TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
19471
19472
0
    for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
19473
0
    {
19474
0
        if (pcmd->UserCallback)
19475
0
        {
19476
0
            BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
19477
0
            continue;
19478
0
        }
19479
19480
0
        char buf[300];
19481
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
19482
0
            pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
19483
0
            pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
19484
0
        bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
19485
0
        if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
19486
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
19487
0
        if (!pcmd_node_open)
19488
0
            continue;
19489
19490
        // Calculate approximate coverage area (touched pixel count)
19491
        // This will be in pixels squared as long there's no post-scaling happening to the renderer output.
19492
0
        const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
19493
0
        const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
19494
0
        float total_area = 0.0f;
19495
0
        for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
19496
0
        {
19497
0
            ImVec2 triangle[3];
19498
0
            for (int n = 0; n < 3; n++, idx_n++)
19499
0
                triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
19500
0
            total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
19501
0
        }
19502
19503
        // Display vertex information summary. Hover to get all triangles drawn in wire-frame
19504
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
19505
0
        Selectable(buf);
19506
0
        if (IsItemHovered() && fg_draw_list)
19507
0
            DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
19508
19509
        // Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
19510
0
        ImGuiListClipper clipper;
19511
0
        clipper.Begin(pcmd->ElemCount / 3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
19512
0
        while (clipper.Step())
19513
0
            for (int prim = clipper.DisplayStart, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
19514
0
            {
19515
0
                char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
19516
0
                ImVec2 triangle[3];
19517
0
                for (int n = 0; n < 3; n++, idx_i++)
19518
0
                {
19519
0
                    const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
19520
0
                    triangle[n] = v.pos;
19521
0
                    buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
19522
0
                        (n == 0) ? "Vert:" : "     ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
19523
0
                }
19524
19525
0
                Selectable(buf, false);
19526
0
                if (fg_draw_list && IsItemHovered())
19527
0
                {
19528
0
                    ImDrawListFlags backup_flags = fg_draw_list->Flags;
19529
0
                    fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19530
0
                    fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
19531
0
                    fg_draw_list->Flags = backup_flags;
19532
0
                }
19533
0
            }
19534
0
        TreePop();
19535
0
    }
19536
0
    TreePop();
19537
0
}
19538
19539
// [DEBUG] Display mesh/aabb of a ImDrawCmd
19540
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
19541
0
{
19542
0
    IM_ASSERT(show_mesh || show_aabb);
19543
19544
    // Draw wire-frame version of all triangles
19545
0
    ImRect clip_rect = draw_cmd->ClipRect;
19546
0
    ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
19547
0
    ImDrawListFlags backup_flags = out_draw_list->Flags;
19548
0
    out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
19549
0
    for (unsigned int idx_n = draw_cmd->IdxOffset, idx_end = draw_cmd->IdxOffset + draw_cmd->ElemCount; idx_n < idx_end; )
19550
0
    {
19551
0
        ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL; // We don't hold on those pointers past iterations as ->AddPolyline() may invalidate them if out_draw_list==draw_list
19552
0
        ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
19553
19554
0
        ImVec2 triangle[3];
19555
0
        for (int n = 0; n < 3; n++, idx_n++)
19556
0
            vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
19557
0
        if (show_mesh)
19558
0
            out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
19559
0
    }
19560
    // Draw bounding boxes
19561
0
    if (show_aabb)
19562
0
    {
19563
0
        out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
19564
0
        out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
19565
0
    }
19566
0
    out_draw_list->Flags = backup_flags;
19567
0
}
19568
19569
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
19570
void ImGui::DebugNodeFont(ImFont* font)
19571
0
{
19572
0
    bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
19573
0
        font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
19574
0
    SameLine();
19575
0
    if (SmallButton("Set as default"))
19576
0
        GetIO().FontDefault = font;
19577
0
    if (!opened)
19578
0
        return;
19579
19580
    // Display preview text
19581
0
    PushFont(font);
19582
0
    Text("The quick brown fox jumps over the lazy dog");
19583
0
    PopFont();
19584
19585
    // Display details
19586
0
    SetNextItemWidth(GetFontSize() * 8);
19587
0
    DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
19588
0
    SameLine(); MetricsHelpMarker(
19589
0
        "Note than the default embedded font is NOT meant to be scaled.\n\n"
19590
0
        "Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
19591
0
        "You may oversample them to get some flexibility with scaling. "
19592
0
        "You can also render at multiple sizes and select which one to use at runtime.\n\n"
19593
0
        "(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
19594
0
    Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
19595
0
    char c_str[5];
19596
0
    Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
19597
0
    Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
19598
0
    const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
19599
0
    Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
19600
0
    for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
19601
0
        if (font->ConfigData)
19602
0
            if (const ImFontConfig* cfg = &font->ConfigData[config_i])
19603
0
                BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
19604
0
                    config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
19605
19606
    // Display all glyphs of the fonts in separate pages of 256 characters
19607
0
    if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
19608
0
    {
19609
0
        ImDrawList* draw_list = GetWindowDrawList();
19610
0
        const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
19611
0
        const float cell_size = font->FontSize * 1;
19612
0
        const float cell_spacing = GetStyle().ItemSpacing.y;
19613
0
        for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
19614
0
        {
19615
            // Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
19616
            // This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
19617
            // is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
19618
0
            if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
19619
0
            {
19620
0
                base += 4096 - 256;
19621
0
                continue;
19622
0
            }
19623
19624
0
            int count = 0;
19625
0
            for (unsigned int n = 0; n < 256; n++)
19626
0
                if (font->FindGlyphNoFallback((ImWchar)(base + n)))
19627
0
                    count++;
19628
0
            if (count <= 0)
19629
0
                continue;
19630
0
            if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
19631
0
                continue;
19632
19633
            // Draw a 16x16 grid of glyphs
19634
0
            ImVec2 base_pos = GetCursorScreenPos();
19635
0
            for (unsigned int n = 0; n < 256; n++)
19636
0
            {
19637
                // We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
19638
                // available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
19639
0
                ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
19640
0
                ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
19641
0
                const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
19642
0
                draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
19643
0
                if (!glyph)
19644
0
                    continue;
19645
0
                font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
19646
0
                if (IsMouseHoveringRect(cell_p1, cell_p2))
19647
0
                {
19648
0
                    BeginTooltip();
19649
0
                    DebugNodeFontGlyph(font, glyph);
19650
0
                    EndTooltip();
19651
0
                }
19652
0
            }
19653
0
            Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
19654
0
            TreePop();
19655
0
        }
19656
0
        TreePop();
19657
0
    }
19658
0
    TreePop();
19659
0
}
19660
19661
void ImGui::DebugNodeFontGlyph(ImFont*, const ImFontGlyph* glyph)
19662
0
{
19663
0
    Text("Codepoint: U+%04X", glyph->Codepoint);
19664
0
    Separator();
19665
0
    Text("Visible: %d", glyph->Visible);
19666
0
    Text("AdvanceX: %.1f", glyph->AdvanceX);
19667
0
    Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
19668
0
    Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
19669
0
}
19670
19671
// [DEBUG] Display contents of ImGuiStorage
19672
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
19673
0
{
19674
0
    if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
19675
0
        return;
19676
0
    for (int n = 0; n < storage->Data.Size; n++)
19677
0
    {
19678
0
        const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
19679
0
        BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
19680
0
    }
19681
0
    TreePop();
19682
0
}
19683
19684
// [DEBUG] Display contents of ImGuiTabBar
19685
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
19686
0
{
19687
    // Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
19688
0
    char buf[256];
19689
0
    char* p = buf;
19690
0
    const char* buf_end = buf + IM_ARRAYSIZE(buf);
19691
0
    const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
19692
0
    p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
19693
0
    p += ImFormatString(p, buf_end - p, "  { ");
19694
0
    for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
19695
0
    {
19696
0
        ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19697
0
        p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", TabBarGetTabName(tab_bar, tab));
19698
0
    }
19699
0
    p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
19700
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19701
0
    bool open = TreeNode(label, "%s", buf);
19702
0
    if (!is_active) { PopStyleColor(); }
19703
0
    if (is_active && IsItemHovered())
19704
0
    {
19705
0
        ImDrawList* draw_list = GetForegroundDrawList();
19706
0
        draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
19707
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19708
0
        draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
19709
0
    }
19710
0
    if (open)
19711
0
    {
19712
0
        for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
19713
0
        {
19714
0
            ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
19715
0
            PushID(tab);
19716
0
            if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
19717
0
            if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
19718
0
            Text("%02d%c Tab 0x%08X '%s' Offset: %.2f, Width: %.2f/%.2f",
19719
0
                tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, TabBarGetTabName(tab_bar, tab), tab->Offset, tab->Width, tab->ContentWidth);
19720
0
            PopID();
19721
0
        }
19722
0
        TreePop();
19723
0
    }
19724
0
}
19725
19726
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
19727
0
{
19728
0
    SetNextItemOpen(true, ImGuiCond_Once);
19729
0
    if (TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
19730
0
    {
19731
0
        ImGuiWindowFlags flags = viewport->Flags;
19732
0
        BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f\nMonitor: %d, DpiScale: %.0f%%",
19733
0
            viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
19734
0
            viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y,
19735
0
            viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
19736
0
        if (viewport->Idx > 0) { SameLine(); if (SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200, 200); viewport->UpdateWorkRect(); if (viewport->Window) viewport->Window->Pos = viewport->Pos; } }
19737
0
        BulletText("Flags: 0x%04X =%s%s%s%s%s%s%s%s%s%s%s%s", viewport->Flags,
19738
            //(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "", // Omitting because it is the standard
19739
0
            (flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
19740
0
            (flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "",
19741
0
            (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
19742
0
            (flags & ImGuiViewportFlags_NoTaskBarIcon) ? " NoTaskBarIcon" : "",
19743
0
            (flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "",
19744
0
            (flags & ImGuiViewportFlags_NoFocusOnClick) ? " NoFocusOnClick" : "",
19745
0
            (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
19746
0
            (flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "",
19747
0
            (flags & ImGuiViewportFlags_TopMost) ? " TopMost" : "",
19748
0
            (flags & ImGuiViewportFlags_Minimized) ? " Minimized" : "",
19749
0
            (flags & ImGuiViewportFlags_NoAutoMerge) ? " NoAutoMerge" : "",
19750
0
            (flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "");
19751
0
        for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
19752
0
            for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
19753
0
                DebugNodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
19754
0
        TreePop();
19755
0
    }
19756
0
}
19757
19758
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
19759
0
{
19760
0
    if (window == NULL)
19761
0
    {
19762
0
        BulletText("%s: NULL", label);
19763
0
        return;
19764
0
    }
19765
19766
0
    ImGuiContext& g = *GImGui;
19767
0
    const bool is_active = window->WasActive;
19768
0
    ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
19769
0
    if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
19770
0
    const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
19771
0
    if (!is_active) { PopStyleColor(); }
19772
0
    if (IsItemHovered() && is_active)
19773
0
        GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
19774
0
    if (!open)
19775
0
        return;
19776
19777
0
    if (window->MemoryCompacted)
19778
0
        TextDisabled("Note: some memory buffers have been compacted/freed.");
19779
19780
0
    ImGuiWindowFlags flags = window->Flags;
19781
0
    DebugNodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
19782
0
    BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
19783
0
    BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
19784
0
        (flags & ImGuiWindowFlags_ChildWindow)  ? "Child " : "",      (flags & ImGuiWindowFlags_Tooltip)     ? "Tooltip "   : "",  (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
19785
0
        (flags & ImGuiWindowFlags_Modal)        ? "Modal " : "",      (flags & ImGuiWindowFlags_ChildMenu)   ? "ChildMenu " : "",  (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
19786
0
        (flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
19787
0
    BulletText("WindowClassId: 0x%08X", window->WindowClass.ClassId);
19788
0
    BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
19789
0
    BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
19790
0
    BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
19791
0
    for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
19792
0
    {
19793
0
        ImRect r = window->NavRectRel[layer];
19794
0
        if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
19795
0
            BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
19796
0
        else
19797
0
            BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
19798
0
        DebugLocateItemOnHover(window->NavLastIds[layer]);
19799
0
    }
19800
0
    BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
19801
19802
0
    BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
19803
0
    BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
19804
0
    BulletText("DockId: 0x%04X, DockOrder: %d, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockIsActive, window->DockTabIsVisible);
19805
0
    if (window->DockNode || window->DockNodeAsHost)
19806
0
        DebugNodeDockNode(window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode");
19807
19808
0
    if (window->RootWindow != window)       { DebugNodeWindow(window->RootWindow, "RootWindow"); }
19809
0
    if (window->RootWindowDockTree != window->RootWindow) { DebugNodeWindow(window->RootWindowDockTree, "RootWindowDockTree"); }
19810
0
    if (window->ParentWindow != NULL)       { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
19811
0
    if (window->DC.ChildWindows.Size > 0)   { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
19812
0
    if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
19813
0
    {
19814
0
        for (int n = 0; n < window->ColumnsStorage.Size; n++)
19815
0
            DebugNodeColumns(&window->ColumnsStorage[n]);
19816
0
        TreePop();
19817
0
    }
19818
0
    DebugNodeStorage(&window->StateStorage, "Storage");
19819
0
    TreePop();
19820
0
}
19821
19822
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
19823
0
{
19824
0
    if (settings->WantDelete)
19825
0
        BeginDisabled();
19826
0
    Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
19827
0
        settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
19828
0
    if (settings->WantDelete)
19829
0
        EndDisabled();
19830
0
}
19831
19832
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
19833
0
{
19834
0
    if (!TreeNode(label, "%s (%d)", label, windows->Size))
19835
0
        return;
19836
0
    for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
19837
0
    {
19838
0
        PushID((*windows)[i]);
19839
0
        DebugNodeWindow((*windows)[i], "Window");
19840
0
        PopID();
19841
0
    }
19842
0
    TreePop();
19843
0
}
19844
19845
// FIXME-OPT: This is technically suboptimal, but it is simpler this way.
19846
void ImGui::DebugNodeWindowsListByBeginStackParent(ImGuiWindow** windows, int windows_size, ImGuiWindow* parent_in_begin_stack)
19847
0
{
19848
0
    for (int i = 0; i < windows_size; i++)
19849
0
    {
19850
0
        ImGuiWindow* window = windows[i];
19851
0
        if (window->ParentWindowInBeginStack != parent_in_begin_stack)
19852
0
            continue;
19853
0
        char buf[20];
19854
0
        ImFormatString(buf, IM_ARRAYSIZE(buf), "[%04d] Window", window->BeginOrderWithinContext);
19855
        //BulletText("[%04d] Window '%s'", window->BeginOrderWithinContext, window->Name);
19856
0
        DebugNodeWindow(window, buf);
19857
0
        Indent();
19858
0
        DebugNodeWindowsListByBeginStackParent(windows + i + 1, windows_size - i - 1, window);
19859
0
        Unindent();
19860
0
    }
19861
0
}
19862
19863
//-----------------------------------------------------------------------------
19864
// [SECTION] DEBUG LOG WINDOW
19865
//-----------------------------------------------------------------------------
19866
19867
void ImGui::DebugLog(const char* fmt, ...)
19868
0
{
19869
0
    va_list args;
19870
0
    va_start(args, fmt);
19871
0
    DebugLogV(fmt, args);
19872
0
    va_end(args);
19873
0
}
19874
19875
void ImGui::DebugLogV(const char* fmt, va_list args)
19876
0
{
19877
0
    ImGuiContext& g = *GImGui;
19878
0
    const int old_size = g.DebugLogBuf.size();
19879
0
    g.DebugLogBuf.appendf("[%05d] ", g.FrameCount);
19880
0
    g.DebugLogBuf.appendfv(fmt, args);
19881
0
    if (g.DebugLogFlags & ImGuiDebugLogFlags_OutputToTTY)
19882
0
        IMGUI_DEBUG_PRINTF("%s", g.DebugLogBuf.begin() + old_size);
19883
0
    g.DebugLogIndex.append(g.DebugLogBuf.c_str(), old_size, g.DebugLogBuf.size());
19884
0
}
19885
19886
void ImGui::ShowDebugLogWindow(bool* p_open)
19887
0
{
19888
0
    ImGuiContext& g = *GImGui;
19889
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
19890
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 12.0f), ImGuiCond_FirstUseEver);
19891
0
    if (!Begin("Dear ImGui Debug Log", p_open) || GetCurrentWindow()->BeginCount > 1)
19892
0
    {
19893
0
        End();
19894
0
        return;
19895
0
    }
19896
19897
0
    AlignTextToFramePadding();
19898
0
    Text("Log events:");
19899
0
    SameLine(); CheckboxFlags("All", &g.DebugLogFlags, ImGuiDebugLogFlags_EventMask_);
19900
0
    SameLine(); CheckboxFlags("ActiveId", &g.DebugLogFlags, ImGuiDebugLogFlags_EventActiveId);
19901
0
    SameLine(); CheckboxFlags("Focus", &g.DebugLogFlags, ImGuiDebugLogFlags_EventFocus);
19902
0
    SameLine(); CheckboxFlags("Popup", &g.DebugLogFlags, ImGuiDebugLogFlags_EventPopup);
19903
0
    SameLine(); CheckboxFlags("Nav", &g.DebugLogFlags, ImGuiDebugLogFlags_EventNav);
19904
0
    SameLine(); CheckboxFlags("Clipper", &g.DebugLogFlags, ImGuiDebugLogFlags_EventClipper);
19905
0
    SameLine(); CheckboxFlags("IO", &g.DebugLogFlags, ImGuiDebugLogFlags_EventIO);
19906
0
    SameLine(); CheckboxFlags("Docking", &g.DebugLogFlags, ImGuiDebugLogFlags_EventDocking);
19907
0
    SameLine(); CheckboxFlags("Viewport", &g.DebugLogFlags, ImGuiDebugLogFlags_EventViewport);
19908
19909
0
    if (SmallButton("Clear"))
19910
0
    {
19911
0
        g.DebugLogBuf.clear();
19912
0
        g.DebugLogIndex.clear();
19913
0
    }
19914
0
    SameLine();
19915
0
    if (SmallButton("Copy"))
19916
0
        SetClipboardText(g.DebugLogBuf.c_str());
19917
0
    BeginChild("##log", ImVec2(0.0f, 0.0f), true, ImGuiWindowFlags_AlwaysVerticalScrollbar | ImGuiWindowFlags_AlwaysHorizontalScrollbar);
19918
19919
0
    ImGuiListClipper clipper;
19920
0
    clipper.Begin(g.DebugLogIndex.size());
19921
0
    while (clipper.Step())
19922
0
        for (int line_no = clipper.DisplayStart; line_no < clipper.DisplayEnd; line_no++)
19923
0
        {
19924
0
            const char* line_begin = g.DebugLogIndex.get_line_begin(g.DebugLogBuf.c_str(), line_no);
19925
0
            const char* line_end = g.DebugLogIndex.get_line_end(g.DebugLogBuf.c_str(), line_no);
19926
0
            TextUnformatted(line_begin, line_end);
19927
0
            ImRect text_rect = g.LastItemData.Rect;
19928
0
            if (IsItemHovered())
19929
0
                for (const char* p = line_begin; p < line_end - 10; p++)
19930
0
                {
19931
0
                    ImGuiID id = 0;
19932
0
                    if (p[0] != '0' || (p[1] != 'x' && p[1] != 'X') || sscanf(p + 2, "%X", &id) != 1)
19933
0
                        continue;
19934
0
                    ImVec2 p0 = CalcTextSize(line_begin, p);
19935
0
                    ImVec2 p1 = CalcTextSize(p, p + 10);
19936
0
                    g.LastItemData.Rect = ImRect(text_rect.Min + ImVec2(p0.x, 0.0f), text_rect.Min + ImVec2(p0.x + p1.x, p1.y));
19937
0
                    if (IsMouseHoveringRect(g.LastItemData.Rect.Min, g.LastItemData.Rect.Max, true))
19938
0
                        DebugLocateItemOnHover(id);
19939
0
                    p += 10;
19940
0
                }
19941
0
        }
19942
0
    if (GetScrollY() >= GetScrollMaxY())
19943
0
        SetScrollHereY(1.0f);
19944
0
    EndChild();
19945
19946
0
    End();
19947
0
}
19948
19949
//-----------------------------------------------------------------------------
19950
// [SECTION] OTHER DEBUG TOOLS (ITEM PICKER, STACK TOOL)
19951
//-----------------------------------------------------------------------------
19952
19953
static const ImU32 DEBUG_LOCATE_ITEM_COLOR = IM_COL32(0, 255, 0, 255);  // Green
19954
19955
void ImGui::DebugLocateItem(ImGuiID target_id)
19956
0
{
19957
0
    ImGuiContext& g = *GImGui;
19958
0
    g.DebugLocateId = target_id;
19959
0
    g.DebugLocateFrames = 2;
19960
0
}
19961
19962
void ImGui::DebugLocateItemOnHover(ImGuiID target_id)
19963
0
{
19964
0
    if (target_id == 0 || !IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem | ImGuiHoveredFlags_AllowWhenBlockedByPopup))
19965
0
        return;
19966
0
    ImGuiContext& g = *GImGui;
19967
0
    DebugLocateItem(target_id);
19968
0
    GetForegroundDrawList(g.CurrentWindow)->AddRect(g.LastItemData.Rect.Min - ImVec2(3.0f, 3.0f), g.LastItemData.Rect.Max + ImVec2(3.0f, 3.0f), DEBUG_LOCATE_ITEM_COLOR);
19969
0
}
19970
19971
void ImGui::DebugLocateItemResolveWithLastItem()
19972
0
{
19973
0
    ImGuiContext& g = *GImGui;
19974
0
    ImGuiLastItemData item_data = g.LastItemData;
19975
0
    g.DebugLocateId = 0;
19976
0
    ImDrawList* draw_list = GetForegroundDrawList(g.CurrentWindow);
19977
0
    ImRect r = item_data.Rect;
19978
0
    r.Expand(3.0f);
19979
0
    ImVec2 p1 = g.IO.MousePos;
19980
0
    ImVec2 p2 = ImVec2((p1.x < r.Min.x) ? r.Min.x : (p1.x > r.Max.x) ? r.Max.x : p1.x, (p1.y < r.Min.y) ? r.Min.y : (p1.y > r.Max.y) ? r.Max.y : p1.y);
19981
0
    draw_list->AddRect(r.Min, r.Max, DEBUG_LOCATE_ITEM_COLOR);
19982
0
    draw_list->AddLine(p1, p2, DEBUG_LOCATE_ITEM_COLOR);
19983
0
}
19984
19985
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
19986
void ImGui::UpdateDebugToolItemPicker()
19987
34.4k
{
19988
34.4k
    ImGuiContext& g = *GImGui;
19989
34.4k
    g.DebugItemPickerBreakId = 0;
19990
34.4k
    if (!g.DebugItemPickerActive)
19991
34.4k
        return;
19992
19993
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
19994
0
    SetMouseCursor(ImGuiMouseCursor_Hand);
19995
0
    if (IsKeyPressed(ImGuiKey_Escape))
19996
0
        g.DebugItemPickerActive = false;
19997
0
    const bool change_mapping = g.IO.KeyMods == (ImGuiMod_Ctrl | ImGuiMod_Shift);
19998
0
    if (!change_mapping && IsMouseClicked(g.DebugItemPickerMouseButton) && hovered_id)
19999
0
    {
20000
0
        g.DebugItemPickerBreakId = hovered_id;
20001
0
        g.DebugItemPickerActive = false;
20002
0
    }
20003
0
    for (int mouse_button = 0; mouse_button < 3; mouse_button++)
20004
0
        if (change_mapping && IsMouseClicked(mouse_button))
20005
0
            g.DebugItemPickerMouseButton = (ImU8)mouse_button;
20006
0
    SetNextWindowBgAlpha(0.70f);
20007
0
    BeginTooltip();
20008
0
    Text("HoveredId: 0x%08X", hovered_id);
20009
0
    Text("Press ESC to abort picking.");
20010
0
    const char* mouse_button_names[] = { "Left", "Right", "Middle" };
20011
0
    if (change_mapping)
20012
0
        Text("Remap w/ Ctrl+Shift: click anywhere to select new mouse button.");
20013
0
    else
20014
0
        TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click %s Button to break in debugger! (remap w/ Ctrl+Shift)", mouse_button_names[g.DebugItemPickerMouseButton]);
20015
0
    EndTooltip();
20016
0
}
20017
20018
// [DEBUG] Stack Tool: update queries. Called by NewFrame()
20019
void ImGui::UpdateDebugToolStackQueries()
20020
34.4k
{
20021
34.4k
    ImGuiContext& g = *GImGui;
20022
34.4k
    ImGuiStackTool* tool = &g.DebugStackTool;
20023
20024
    // Clear hook when stack tool is not visible
20025
34.4k
    g.DebugHookIdInfo = 0;
20026
34.4k
    if (g.FrameCount != tool->LastActiveFrame + 1)
20027
34.4k
        return;
20028
20029
    // Update queries. The steps are: -1: query Stack, >= 0: query each stack item
20030
    // We can only perform 1 ID Info query every frame. This is designed so the GetID() tests are cheap and constant-time
20031
3
    const ImGuiID query_id = g.HoveredIdPreviousFrame ? g.HoveredIdPreviousFrame : g.ActiveId;
20032
3
    if (tool->QueryId != query_id)
20033
0
    {
20034
0
        tool->QueryId = query_id;
20035
0
        tool->StackLevel = -1;
20036
0
        tool->Results.resize(0);
20037
0
    }
20038
3
    if (query_id == 0)
20039
3
        return;
20040
20041
    // Advance to next stack level when we got our result, or after 2 frames (in case we never get a result)
20042
0
    int stack_level = tool->StackLevel;
20043
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20044
0
        if (tool->Results[stack_level].QuerySuccess || tool->Results[stack_level].QueryFrameCount > 2)
20045
0
            tool->StackLevel++;
20046
20047
    // Update hook
20048
0
    stack_level = tool->StackLevel;
20049
0
    if (stack_level == -1)
20050
0
        g.DebugHookIdInfo = query_id;
20051
0
    if (stack_level >= 0 && stack_level < tool->Results.Size)
20052
0
    {
20053
0
        g.DebugHookIdInfo = tool->Results[stack_level].ID;
20054
0
        tool->Results[stack_level].QueryFrameCount++;
20055
0
    }
20056
0
}
20057
20058
// [DEBUG] Stack tool: hooks called by GetID() family functions
20059
void ImGui::DebugHookIdInfo(ImGuiID id, ImGuiDataType data_type, const void* data_id, const void* data_id_end)
20060
0
{
20061
0
    ImGuiContext& g = *GImGui;
20062
0
    ImGuiWindow* window = g.CurrentWindow;
20063
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20064
20065
    // Step 0: stack query
20066
    // This assumes that the ID was computed with the current ID stack, which tends to be the case for our widget.
20067
0
    if (tool->StackLevel == -1)
20068
0
    {
20069
0
        tool->StackLevel++;
20070
0
        tool->Results.resize(window->IDStack.Size + 1, ImGuiStackLevelInfo());
20071
0
        for (int n = 0; n < window->IDStack.Size + 1; n++)
20072
0
            tool->Results[n].ID = (n < window->IDStack.Size) ? window->IDStack[n] : id;
20073
0
        return;
20074
0
    }
20075
20076
    // Step 1+: query for individual level
20077
0
    IM_ASSERT(tool->StackLevel >= 0);
20078
0
    if (tool->StackLevel != window->IDStack.Size)
20079
0
        return;
20080
0
    ImGuiStackLevelInfo* info = &tool->Results[tool->StackLevel];
20081
0
    IM_ASSERT(info->ID == id && info->QueryFrameCount > 0);
20082
20083
0
    switch (data_type)
20084
0
    {
20085
0
    case ImGuiDataType_S32:
20086
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%d", (int)(intptr_t)data_id);
20087
0
        break;
20088
0
    case ImGuiDataType_String:
20089
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "%.*s", data_id_end ? (int)((const char*)data_id_end - (const char*)data_id) : (int)strlen((const char*)data_id), (const char*)data_id);
20090
0
        break;
20091
0
    case ImGuiDataType_Pointer:
20092
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "(void*)0x%p", data_id);
20093
0
        break;
20094
0
    case ImGuiDataType_ID:
20095
0
        if (info->Desc[0] != 0) // PushOverrideID() is often used to avoid hashing twice, which would lead to 2 calls to DebugHookIdInfo(). We prioritize the first one.
20096
0
            return;
20097
0
        ImFormatString(info->Desc, IM_ARRAYSIZE(info->Desc), "0x%08X [override]", id);
20098
0
        break;
20099
0
    default:
20100
0
        IM_ASSERT(0);
20101
0
    }
20102
0
    info->QuerySuccess = true;
20103
0
    info->DataType = data_type;
20104
0
}
20105
20106
static int StackToolFormatLevelInfo(ImGuiStackTool* tool, int n, bool format_for_ui, char* buf, size_t buf_size)
20107
0
{
20108
0
    ImGuiStackLevelInfo* info = &tool->Results[n];
20109
0
    ImGuiWindow* window = (info->Desc[0] == 0 && n == 0) ? ImGui::FindWindowByID(info->ID) : NULL;
20110
0
    if (window)                                                                 // Source: window name (because the root ID don't call GetID() and so doesn't get hooked)
20111
0
        return ImFormatString(buf, buf_size, format_for_ui ? "\"%s\" [window]" : "%s", window->Name);
20112
0
    if (info->QuerySuccess)                                                     // Source: GetID() hooks (prioritize over ItemInfo() because we frequently use patterns like: PushID(str), Button("") where they both have same id)
20113
0
        return ImFormatString(buf, buf_size, (format_for_ui && info->DataType == ImGuiDataType_String) ? "\"%s\"" : "%s", info->Desc);
20114
0
    if (tool->StackLevel < tool->Results.Size)                                  // Only start using fallback below when all queries are done, so during queries we don't flickering ??? markers.
20115
0
        return (*buf = 0);
20116
#ifdef IMGUI_ENABLE_TEST_ENGINE
20117
    if (const char* label = ImGuiTestEngine_FindItemDebugLabel(GImGui, info->ID))   // Source: ImGuiTestEngine's ItemInfo()
20118
        return ImFormatString(buf, buf_size, format_for_ui ? "??? \"%s\"" : "%s", label);
20119
#endif
20120
0
    return ImFormatString(buf, buf_size, "???");
20121
0
}
20122
20123
// Stack Tool: Display UI
20124
void ImGui::ShowStackToolWindow(bool* p_open)
20125
0
{
20126
0
    ImGuiContext& g = *GImGui;
20127
0
    if (!(g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize))
20128
0
        SetNextWindowSize(ImVec2(0.0f, GetFontSize() * 8.0f), ImGuiCond_FirstUseEver);
20129
0
    if (!Begin("Dear ImGui Stack Tool", p_open) || GetCurrentWindow()->BeginCount > 1)
20130
0
    {
20131
0
        End();
20132
0
        return;
20133
0
    }
20134
20135
    // Display hovered/active status
20136
0
    ImGuiStackTool* tool = &g.DebugStackTool;
20137
0
    const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
20138
0
    const ImGuiID active_id = g.ActiveId;
20139
#ifdef IMGUI_ENABLE_TEST_ENGINE
20140
    Text("HoveredId: 0x%08X (\"%s\"), ActiveId:  0x%08X (\"%s\")", hovered_id, hovered_id ? ImGuiTestEngine_FindItemDebugLabel(&g, hovered_id) : "", active_id, active_id ? ImGuiTestEngine_FindItemDebugLabel(&g, active_id) : "");
20141
#else
20142
0
    Text("HoveredId: 0x%08X, ActiveId:  0x%08X", hovered_id, active_id);
20143
0
#endif
20144
0
    SameLine();
20145
0
    MetricsHelpMarker("Hover an item with the mouse to display elements of the ID Stack leading to the item's final ID.\nEach level of the stack correspond to a PushID() call.\nAll levels of the stack are hashed together to make the final ID of a widget (ID displayed at the bottom level of the stack).\nRead FAQ entry about the ID stack for details.");
20146
20147
    // CTRL+C to copy path
20148
0
    const float time_since_copy = (float)g.Time - tool->CopyToClipboardLastTime;
20149
0
    Checkbox("Ctrl+C: copy path to clipboard", &tool->CopyToClipboardOnCtrlC);
20150
0
    SameLine();
20151
0
    TextColored((time_since_copy >= 0.0f && time_since_copy < 0.75f && ImFmod(time_since_copy, 0.25f) < 0.25f * 0.5f) ? ImVec4(1.f, 1.f, 0.3f, 1.f) : ImVec4(), "*COPIED*");
20152
0
    if (tool->CopyToClipboardOnCtrlC && IsKeyDown(ImGuiMod_Ctrl) && IsKeyPressed(ImGuiKey_C))
20153
0
    {
20154
0
        tool->CopyToClipboardLastTime = (float)g.Time;
20155
0
        char* p = g.TempBuffer.Data;
20156
0
        char* p_end = p + g.TempBuffer.Size;
20157
0
        for (int stack_n = 0; stack_n < tool->Results.Size && p + 3 < p_end; stack_n++)
20158
0
        {
20159
0
            *p++ = '/';
20160
0
            char level_desc[256];
20161
0
            StackToolFormatLevelInfo(tool, stack_n, false, level_desc, IM_ARRAYSIZE(level_desc));
20162
0
            for (int n = 0; level_desc[n] && p + 2 < p_end; n++)
20163
0
            {
20164
0
                if (level_desc[n] == '/')
20165
0
                    *p++ = '\\';
20166
0
                *p++ = level_desc[n];
20167
0
            }
20168
0
        }
20169
0
        *p = '\0';
20170
0
        SetClipboardText(g.TempBuffer.Data);
20171
0
    }
20172
20173
    // Display decorated stack
20174
0
    tool->LastActiveFrame = g.FrameCount;
20175
0
    if (tool->Results.Size > 0 && BeginTable("##table", 3, ImGuiTableFlags_Borders))
20176
0
    {
20177
0
        const float id_width = CalcTextSize("0xDDDDDDDD").x;
20178
0
        TableSetupColumn("Seed", ImGuiTableColumnFlags_WidthFixed, id_width);
20179
0
        TableSetupColumn("PushID", ImGuiTableColumnFlags_WidthStretch);
20180
0
        TableSetupColumn("Result", ImGuiTableColumnFlags_WidthFixed, id_width);
20181
0
        TableHeadersRow();
20182
0
        for (int n = 0; n < tool->Results.Size; n++)
20183
0
        {
20184
0
            ImGuiStackLevelInfo* info = &tool->Results[n];
20185
0
            TableNextColumn();
20186
0
            Text("0x%08X", (n > 0) ? tool->Results[n - 1].ID : 0);
20187
0
            TableNextColumn();
20188
0
            StackToolFormatLevelInfo(tool, n, true, g.TempBuffer.Data, g.TempBuffer.Size);
20189
0
            TextUnformatted(g.TempBuffer.Data);
20190
0
            TableNextColumn();
20191
0
            Text("0x%08X", info->ID);
20192
0
            if (n == tool->Results.Size - 1)
20193
0
                TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_Header));
20194
0
        }
20195
0
        EndTable();
20196
0
    }
20197
0
    End();
20198
0
}
20199
20200
#else
20201
20202
void ImGui::ShowMetricsWindow(bool*) {}
20203
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
20204
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
20205
void ImGui::DebugNodeDrawList(ImGuiWindow*, ImGuiViewportP*, const ImDrawList*, const char*) {}
20206
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
20207
void ImGui::DebugNodeFont(ImFont*) {}
20208
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
20209
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
20210
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
20211
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
20212
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
20213
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
20214
20215
void ImGui::DebugLog(const char*, ...) {}
20216
void ImGui::DebugLogV(const char*, va_list) {}
20217
void ImGui::ShowDebugLogWindow(bool*) {}
20218
void ImGui::ShowStackToolWindow(bool*) {}
20219
void ImGui::DebugHookIdInfo(ImGuiID, ImGuiDataType, const void*, const void*) {}
20220
void ImGui::UpdateDebugToolItemPicker() {}
20221
void ImGui::UpdateDebugToolStackQueries() {}
20222
20223
#endif // #ifndef IMGUI_DISABLE_DEBUG_TOOLS
20224
20225
//-----------------------------------------------------------------------------
20226
20227
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
20228
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
20229
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
20230
#include "imgui_user.inl"
20231
#endif
20232
20233
//-----------------------------------------------------------------------------
20234
20235
#endif // #ifndef IMGUI_DISABLE